diff options
author | rescobar | 2010-06-24 04:48:36 +0000 |
---|---|---|
committer | rescobar | 2010-06-24 04:48:36 +0000 |
commit | 0050dda70a82b360067011444b08c29b44c612b2 (patch) | |
tree | 360da86a1d666475d02fe85804e6831a07a2c37b | |
parent | fa0d10b3271aa558befb3f732084c9917111aaab (diff) | |
download | org.eclipse.osee-0050dda70a82b360067011444b08c29b44c612b2.tar.gz org.eclipse.osee-0050dda70a82b360067011444b08c29b44c612b2.tar.xz org.eclipse.osee-0050dda70a82b360067011444b08c29b44c612b2.zip |
66 files changed, 7957 insertions, 0 deletions
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/.classpath b/plugins/org.eclipse.osee.framework.core.datastore/.classpath new file mode 100644 index 00000000000..8a8f1668cdc --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/.project b/plugins/org.eclipse.osee.framework.core.datastore/.project new file mode 100644 index 00000000000..a423f963804 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/.project @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.osee.framework.core.datastore</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ds.core.builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..52aaf6be2f2 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Jun 21 14:28:08 MST 2010
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.pde.core.prefs b/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 00000000000..e8ad19e4cd1 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,5 @@ +#Mon Jun 21 14:28:08 MST 2010
+eclipse.preferences.version=1
+pluginProject.equinox=false
+pluginProject.extensions=false
+resolve.requirebundle=false
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/META-INF/MANIFEST.MF b/plugins/org.eclipse.osee.framework.core.datastore/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..8dca54d319d --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/META-INF/MANIFEST.MF @@ -0,0 +1,40 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: OSEE Core Datastore +Bundle-SymbolicName: org.eclipse.osee.framework.core.datastore;singleton:=true +Bundle-Version: 0.9.5.qualifier +Bundle-Activator: org.eclipse.osee.framework.core.datastore.internal.Activator +Bundle-Vendor: Eclipse.org +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: org.apache.commons.lang, + org.apache.commons.lang.builder, + org.eclipse.core.runtime, + org.eclipse.core.runtime.jobs, + org.eclipse.osee.framework.branch.management, + org.eclipse.osee.framework.core.data, + org.eclipse.osee.framework.core.enums, + org.eclipse.osee.framework.core.exception, + org.eclipse.osee.framework.core.message, + org.eclipse.osee.framework.core.model, + org.eclipse.osee.framework.core.model.cache, + org.eclipse.osee.framework.core.model.type, + org.eclipse.osee.framework.core.operation, + org.eclipse.osee.framework.core.server, + org.eclipse.osee.framework.core.services, + org.eclipse.osee.framework.core.translation, + org.eclipse.osee.framework.core.util, + org.eclipse.osee.framework.database, + org.eclipse.osee.framework.database.core, + org.eclipse.osee.framework.database.operation, + org.eclipse.osee.framework.jdk.core.persistence, + org.eclipse.osee.framework.jdk.core.type, + org.eclipse.osee.framework.jdk.core.util, + org.eclipse.osee.framework.jdk.core.util.time, + org.eclipse.osee.framework.jdk.core.util.xml, + org.eclipse.osee.framework.logging, + org.osgi.framework;version="1.3.0", + org.osgi.util.tracker +Bundle-ActivationPolicy: lazy +Eclipse-ExtensibleAPI: true +Export-Package: org.eclipse.osee.framework.core.datastore +Service-Component: OSGI-INF/core.osee.schema.resource.xml diff --git a/plugins/org.eclipse.osee.framework.core.datastore/OSGI-INF/core.osee.schema.resource.xml b/plugins/org.eclipse.osee.framework.core.datastore/OSGI-INF/core.osee.schema.resource.xml new file mode 100644 index 00000000000..d9967544900 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/OSGI-INF/core.osee.schema.resource.xml @@ -0,0 +1,7 @@ +<?xml version="1.0"?>
+<component name="core.osee.schema.resource">
+ <implementation class="org.eclipse.osee.framework.core.datastore.internal.CoreOseeSchemaResource"/>
+ <service>
+ <provide interface="org.eclipse.osee.framework.core.datastore.IOseeSchemaResource"/>
+ </service>
+</component>
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/build.properties b/plugins/org.eclipse.osee.framework.core.datastore/build.properties new file mode 100644 index 00000000000..d5c5a0485ec --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/build.properties @@ -0,0 +1,6 @@ +source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ OSGI-INF/,\
+ support/
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/BranchMoveOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/BranchMoveOperation.java new file mode 100644 index 00000000000..b0d0cc40a2f --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/BranchMoveOperation.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2009 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.exception.OseeCoreException; +import org.eclipse.osee.framework.core.model.Branch; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; +import org.eclipse.osee.framework.database.core.AbstractDbTxOperation; +import org.eclipse.osee.framework.database.core.OseeConnection; + +/** + * @author Ryan D. Brooks + */ +public class BranchMoveOperation extends AbstractDbTxOperation { + + private static final String INSERT_ADDRESSING = + "insert into %s (transaction_id, gamma_id, tx_current, mod_type, branch_id) select transaction_id, gamma_id, tx_current, mod_type, branch_id from %s where branch_id = ?"; + + public static final String DELETE_ADDRESSING = "delete from %s where branch_id = ?"; + private final boolean archive; + private final Branch branch; + + public BranchMoveOperation(IOseeDatabaseServiceProvider provider, boolean archive, Branch branch) { + super(provider, "Branch Move", Activator.PLUGIN_ID); + this.archive = archive; + this.branch = branch; + } + + @Override + protected void doTxWork(IProgressMonitor monitor, OseeConnection connection) throws OseeCoreException { + String sourceTableName = archive ? "osee_txs" : "osee_txs_archived"; + String destinationTableName = archive ? "osee_txs_archived" : "osee_txs"; + + String sql = String.format(INSERT_ADDRESSING, destinationTableName, sourceTableName); + getDatabaseService().runPreparedUpdate(connection, sql, branch.getId()); + + sql = String.format(DELETE_ADDRESSING, sourceTableName); + getDatabaseService().runPreparedUpdate(connection, sql, branch.getId()); + } + +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/DatastoreInitOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/DatastoreInitOperation.java new file mode 100644 index 00000000000..c9ca099be70 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/DatastoreInitOperation.java @@ -0,0 +1,90 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore;
+
+import java.io.File;
+import java.util.logging.Level;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.osee.framework.branch.management.IOseeBranchServiceProvider;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.operations.OperationFactory;
+import org.eclipse.osee.framework.core.enums.PermissionEnum;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.operation.AbstractOperation;
+import org.eclipse.osee.framework.core.operation.IOperation;
+import org.eclipse.osee.framework.core.server.IApplicationServerManager;
+import org.eclipse.osee.framework.core.server.OseeServerProperties;
+import org.eclipse.osee.framework.core.util.Conditions;
+import org.eclipse.osee.framework.database.IOseeDatabaseService;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.OseeInfo;
+import org.eclipse.osee.framework.jdk.core.util.GUID;
+import org.eclipse.osee.framework.jdk.core.util.Lib;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatastoreInitOperation extends AbstractOperation {
+
+ private static final String ADD_PERMISSION =
+ "INSERT INTO OSEE_PERMISSION (PERMISSION_ID, PERMISSION_NAME) VALUES (?,?)";
+
+ private final IOseeBranchServiceProvider branchServiceProvider;
+ private final IOseeDatabaseServiceProvider dbService;
+ private final IOseeSchemaProvider schemaProvider;
+ private final SchemaCreationOptions options;
+ private final IApplicationServerManager appServerManager;
+
+ public DatastoreInitOperation(IApplicationServerManager appServerManager, IOseeDatabaseServiceProvider dbService, IOseeBranchServiceProvider branchServiceProvider, IOseeSchemaProvider schemaProvider, SchemaCreationOptions options) {
+ super("Datastore Initialization", Activator.PLUGIN_ID);
+ this.appServerManager= appServerManager;
+ this.dbService = dbService;
+ this.branchServiceProvider = branchServiceProvider;
+ this.schemaProvider = schemaProvider;
+ this.options = options;
+ }
+
+ @Override
+ protected void doWork(IProgressMonitor monitor) throws Exception {
+ Conditions.checkExpressionFailOnTrue(dbService.getOseeDatabaseService().isProduction(),
+ "Error - attempting to initialize a production datastore.");
+
+ IOperation subOp = OperationFactory.createDbSchema(dbService, schemaProvider, options);
+ doSubWork(subOp, monitor, 0.30);
+ appServerManager.executeLookupRegistration();
+
+ deleteBinaryBackingData();
+ String binaryDataPath = OseeServerProperties.getOseeApplicationServerData();
+ Lib.deleteDir(new File(binaryDataPath + File.separator + "attr"));
+
+ OseeInfo.putValue(OseeInfo.DB_ID_KEY, GUID.create());
+ addDefaultPermissions();
+
+ subOp = branchServiceProvider.getBranchService().createSystemRootBranch(monitor);
+ doSubWork(subOp, monitor, 0.30);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addDefaultPermissions() throws OseeDataStoreException {
+ IOseeDatabaseService service = dbService.getOseeDatabaseService();
+ for (PermissionEnum permission : PermissionEnum.values()) {
+ service.runPreparedUpdate(ADD_PERMISSION, permission.getPermId(), permission.getName());
+ }
+ }
+
+ private static void deleteBinaryBackingData() {
+ String binaryDataPath = OseeServerProperties.getOseeApplicationServerData();
+ OseeLog.log(Activator.class, Level.INFO, String.format("Deleting application server binary data [%s]...",
+ binaryDataPath));
+ Lib.deleteDir(new File(binaryDataPath + File.separator + "attr"));
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaProvider.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaProvider.java new file mode 100644 index 00000000000..c579500bbb5 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaProvider.java @@ -0,0 +1,22 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore;
+
+import java.util.Collection;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public interface IOseeSchemaProvider {
+
+ Collection<IOseeSchemaResource> getSchemaResources();
+
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaResource.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaResource.java new file mode 100644 index 00000000000..3dea7eece43 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/IOseeSchemaResource.java @@ -0,0 +1,22 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore;
+
+import java.io.InputStream;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public interface IOseeSchemaResource {
+
+ public InputStream getContent() throws OseeCoreException;
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/OseeSchemaProvider.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/OseeSchemaProvider.java new file mode 100644 index 00000000000..cb35f6044e2 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/OseeSchemaProvider.java @@ -0,0 +1,42 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import org.eclipse.core.runtime.Platform;
+import org.osgi.framework.Bundle;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class OseeSchemaProvider implements IOseeSchemaProvider {
+
+ public Collection<IOseeSchemaResource> getSchemaResources() {
+ Collection<IOseeSchemaResource> providers = new ArrayList<IOseeSchemaResource>();
+
+ Bundle bundle = Platform.getBundle("org.eclipse.osee.framework.core.datastore");
+ ServiceTracker serviceTracker =
+ new ServiceTracker(bundle.getBundleContext(), IOseeSchemaResource.class.getName(), null);
+ serviceTracker.open(true);
+ Object[] services = serviceTracker.getServices();
+ if (services != null) {
+ for (Object object : services) {
+ if (object instanceof IOseeSchemaResource) {
+ providers.add((IOseeSchemaResource) object);
+ }
+ }
+ }
+ serviceTracker.close();
+ return providers;
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/SchemaCreationOptions.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/SchemaCreationOptions.java new file mode 100644 index 00000000000..ed699f4d24f --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/SchemaCreationOptions.java @@ -0,0 +1,50 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore;
+
+import org.eclipse.osee.framework.jdk.core.util.Strings;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class SchemaCreationOptions {
+
+ private final String tableDataSpace;
+ private final String indexDataSpace;
+ private final boolean useFileSpecifiedSchemas;
+
+ public SchemaCreationOptions(String tableDataSpace, String indexDataSpace, boolean useFileSpecifiedSchemas) {
+ super();
+ this.tableDataSpace = tableDataSpace;
+ this.indexDataSpace = indexDataSpace;
+ this.useFileSpecifiedSchemas = useFileSpecifiedSchemas;
+ }
+
+ public String getTableDataSpace() {
+ return tableDataSpace;
+ }
+
+ public String getIndexDataSpace() {
+ return indexDataSpace;
+ }
+
+ public boolean isUseFileSpecifiedSchemas() {
+ return useFileSpecifiedSchemas;
+ }
+
+ public boolean isIndexDataSpaceValid() {
+ return Strings.isValid(getIndexDataSpace());
+ }
+
+ public boolean isTableDataSpaceValid() {
+ return Strings.isValid(getTableDataSpace());
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/AbstractDatabaseAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/AbstractDatabaseAccessor.java new file mode 100644 index 00000000000..34f18cfeda6 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/AbstractDatabaseAccessor.java @@ -0,0 +1,51 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.model.IOseeStorable;
+import org.eclipse.osee.framework.core.model.cache.IOseeDataAccessor;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryService;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseService;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeSequence;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public abstract class AbstractDatabaseAccessor<T extends IOseeStorable> implements IOseeDataAccessor<T> {
+
+ private final IOseeDatabaseServiceProvider databaseProvider;
+ private final IOseeModelFactoryServiceProvider factoryProvider;
+
+ protected AbstractDatabaseAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider) {
+ this.databaseProvider = databaseProvider;
+ this.factoryProvider = factoryProvider;
+ }
+
+ protected IOseeDatabaseServiceProvider getDatabaseServiceProvider() {
+ return databaseProvider;
+ }
+
+ protected IOseeDatabaseService getDatabaseService() throws OseeDataStoreException {
+ return getDatabaseServiceProvider().getOseeDatabaseService();
+ }
+
+ protected IOseeSequence getSequence() throws OseeDataStoreException {
+ return getDatabaseService().getSequence();
+ }
+
+ protected IOseeModelFactoryService getFactoryService() throws OseeCoreException {
+ return factoryProvider.getOseeFactoryService();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchStoreOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchStoreOperation.java new file mode 100644 index 00000000000..35d7ea4e22d --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchStoreOperation.java @@ -0,0 +1,134 @@ +/******************************************************************************* + * Copyright (c) 2009 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.cache; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.logging.Level; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.BranchMoveOperation; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.exception.OseeCoreException; +import org.eclipse.osee.framework.core.exception.OseeDataStoreException; +import org.eclipse.osee.framework.core.model.AbstractOseeType; +import org.eclipse.osee.framework.core.model.Branch; +import org.eclipse.osee.framework.core.model.BranchField; +import org.eclipse.osee.framework.core.model.TransactionRecord; +import org.eclipse.osee.framework.core.operation.Operations; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; +import org.eclipse.osee.framework.database.core.AbstractDbTxOperation; +import org.eclipse.osee.framework.database.core.OseeConnection; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Ryan D. Brooks + */ +public class BranchStoreOperation extends AbstractDbTxOperation { + protected static final int NULL_PARENT_BRANCH_ID = -1; + + private static final String INSERT_BRANCH = + "INSERT INTO osee_branch (branch_id, branch_guid, branch_name, parent_branch_id, parent_transaction_id, archived, associated_art_id, branch_type, branch_state, baseline_transaction_id) VALUES (?,?,?,?,?,?,?,?,?,?)"; + + private static final String UPDATE_BRANCH = + "update osee_branch SET branch_name = ?, parent_branch_id = ?, parent_transaction_id = ?, archived = ?, associated_art_id = ?, branch_type = ?, branch_state = ?, baseline_transaction_id = ? where branch_id = ?"; + + private static final String DELETE_BRANCH = "DELETE from osee_branch where branch_id = ?"; + + private final IBranchUpdateEvent eventSender; + private final Collection<Branch> branches; + + public BranchStoreOperation(IOseeDatabaseServiceProvider provider, IBranchUpdateEvent eventSender, Collection<Branch> branches) { + super(provider, "Branch Archive Operation", Activator.PLUGIN_ID); + this.eventSender = eventSender; + this.branches = branches; + } + + private Object[] toInsertValues(Branch branch) throws OseeCoreException { + Branch parentBranch = branch.getParentBranch(); + TransactionRecord baseTxRecord = branch.getBaseTransaction(); + int parentBranchId = parentBranch != null ? parentBranch.getId() : NULL_PARENT_BRANCH_ID; + int baselineTransaction = baseTxRecord != null ? baseTxRecord.getId() : NULL_PARENT_BRANCH_ID; + + return new Object[] {branch.getId(), branch.getGuid(), branch.getName(), parentBranchId, + branch.getSourceTransaction().getId(), branch.getArchiveState().getValue(), + branch.getAssociatedArtifact().getArtId(), branch.getBranchType().getValue(), + branch.getBranchState().getValue(), baselineTransaction}; + } + + private Object[] toUpdateValues(Branch branch) throws OseeCoreException { + Branch parentBranch = branch.getParentBranch(); + TransactionRecord baseTxRecord = branch.getBaseTransaction(); + int parentBranchId = parentBranch != null ? parentBranch.getId() : NULL_PARENT_BRANCH_ID; + int baselineTransaction = baseTxRecord != null ? baseTxRecord.getId() : NULL_PARENT_BRANCH_ID; + return new Object[] {branch.getName(), parentBranchId, branch.getSourceTransaction().getId(), + branch.getArchiveState().getValue(), branch.getAssociatedArtifact().getArtId(), + branch.getBranchType().getValue(), branch.getBranchState().getValue(), baselineTransaction, branch.getId()}; + } + + private Object[] toDeleteValues(Branch branch) throws OseeDataStoreException { + return new Object[] {branch.getId()}; + } + + @Override + protected void doTxWork(IProgressMonitor monitor, OseeConnection connection) throws OseeCoreException { + List<Object[]> insertData = new ArrayList<Object[]>(); + List<Object[]> updateData = new ArrayList<Object[]>(); + List<Object[]> deleteData = new ArrayList<Object[]>(); + + for (Branch branch : branches) { + if (isDataDirty(branch)) { + switch (branch.getStorageState()) { + case CREATED: + branch.setId(getDatabaseService().getSequence().getNextBranchId()); + insertData.add(toInsertValues(branch)); + break; + case MODIFIED: + updateData.add(toUpdateValues(branch)); + break; + case PURGED: + deleteData.add(toDeleteValues(branch)); + break; + default: + break; + } + } + if (branch.isFieldDirty(BranchField.BRANCH_ARCHIVED_STATE_FIELD_KEY)) { + Operations.executeAsJob(new BranchMoveOperation(getDatabaseServiceProvider(), + branch.getArchiveState().isArchived(), branch), false); + } + + } + getDatabaseService().runBatchUpdate(connection, INSERT_BRANCH, insertData); + getDatabaseService().runBatchUpdate(connection, UPDATE_BRANCH, updateData); + getDatabaseService().runBatchUpdate(connection, DELETE_BRANCH, deleteData); + + for (Branch branch : branches) { + branch.clearDirty(); + } + try { + eventSender.send(branches); + } catch (OseeCoreException ex) { + OseeLog.log(Activator.class, Level.SEVERE, "Error creating branch update relay", ex); + } + } + + private boolean isDataDirty(Branch type) throws OseeCoreException { + return type.areFieldsDirty(// + AbstractOseeType.NAME_FIELD_KEY, // + AbstractOseeType.UNIQUE_ID_FIELD_KEY, // + BranchField.BRANCH_ARCHIVED_STATE_FIELD_KEY, // + BranchField.BRANCH_STATE_FIELD_KEY, // + BranchField.BRANCH_TYPE_FIELD_KEY, // + BranchField.BRANCH_ASSOCIATED_ARTIFACT_FIELD_KEY, // + BranchField.BRANCH_BASE_TRANSACTION); + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchUpdateEventImpl.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchUpdateEventImpl.java new file mode 100644 index 00000000000..162b09a2955 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/BranchUpdateEventImpl.java @@ -0,0 +1,134 @@ +/*
+ * Created on Dec 9, 2009
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.osee.framework.core.data.OseeServerContext;
+import org.eclipse.osee.framework.core.data.OseeServerInfo;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.CacheOperation;
+import org.eclipse.osee.framework.core.enums.CoreTranslatorId;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.message.BranchCacheStoreRequest;
+import org.eclipse.osee.framework.core.message.BranchRow;
+import org.eclipse.osee.framework.core.model.Branch;
+import org.eclipse.osee.framework.core.operation.AbstractOperation;
+import org.eclipse.osee.framework.core.operation.Operations;
+import org.eclipse.osee.framework.core.server.IApplicationServerLookupProvider;
+import org.eclipse.osee.framework.core.server.IApplicationServerManager;
+import org.eclipse.osee.framework.core.translation.IDataTranslationServiceProvider;
+import org.eclipse.osee.framework.core.util.HttpMessage;
+import org.eclipse.osee.framework.core.util.HttpProcessor.AcquireResult;
+import org.eclipse.osee.framework.jdk.core.util.HttpUrlBuilder;
+import org.eclipse.osee.framework.jdk.core.util.Strings;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class BranchUpdateEventImpl implements IBranchUpdateEvent {
+
+ private final IDataTranslationServiceProvider txProvider;
+ private final IApplicationServerLookupProvider lookUpProvider;
+ private final IApplicationServerManager manager;
+
+ public BranchUpdateEventImpl(IDataTranslationServiceProvider translationService, IApplicationServerManager manager, IApplicationServerLookupProvider lookUpProvider) {
+ super();
+ this.txProvider = translationService;
+ this.lookUpProvider = lookUpProvider;
+ this.manager = manager;
+ }
+
+ public void send(final Collection<Branch> branches) throws OseeCoreException {
+ List<Branch> branchToUpdate = new ArrayList<Branch>();
+ for (Branch branch : branches) {
+ if (!branch.isDirty()) {
+ branchToUpdate.add(branch);
+ }
+ }
+ Operations.executeAsJob(new ServerSyncOperation(branchToUpdate), false);
+ }
+
+ private final class ServerSyncOperation extends AbstractOperation {
+
+ private final Collection<Branch> branches;
+
+ public ServerSyncOperation(Collection<Branch> branches) {
+ super("Server Sync", Activator.PLUGIN_ID);
+ this.branches = branches;
+ }
+
+ private boolean is_0_9_2_Compatible(String... versions) {
+ for (String version : versions) {
+ if (Strings.isValid(version)) {
+ String toCheck = version.toLowerCase();
+ if (!toCheck.startsWith("0.9.0") && !toCheck.startsWith("0.9.1")) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private StorageState getCompatibleState(StorageState state) {
+ StorageState toReturn = state;
+ if (state == StorageState.PURGED) {
+ toReturn = StorageState.DELETED;
+ } else if (state == StorageState.LOADED) {
+ toReturn = StorageState.MODIFIED;
+ }
+ return toReturn;
+ }
+
+ @Override
+ protected void doWork(IProgressMonitor monitor) throws Exception {
+ BranchCacheStoreRequest request = BranchCacheStoreRequest.fromCache(branches);
+ request.setServerUpdateMessage(true);
+
+ BranchCacheStoreRequest request0_9_1 = BranchCacheStoreRequest.fromCache(branches);
+ request0_9_1.setServerUpdateMessage(true);
+ for (BranchRow row : request0_9_1.getBranchRows()) {
+ row.setStorageState(getCompatibleState(row.getStorageState()));
+ }
+
+ Map<String, String> parameters = new HashMap<String, String>();
+ parameters.put("function", CacheOperation.STORE.name());
+
+ for (OseeServerInfo serverInfo : lookUpProvider.getApplicationServerLookupService().getAvailableServers()) {
+ if (!manager.getId().equals(serverInfo.getServerId()) && serverInfo.isAcceptingRequests()) {
+ try {
+
+ String urlString =
+ HttpUrlBuilder.createURL(serverInfo.getServerAddress(), serverInfo.getPort(),
+ OseeServerContext.CACHE_CONTEXT, parameters);
+
+ BranchCacheStoreRequest message =
+ is_0_9_2_Compatible(serverInfo.getVersion()) ? request : request0_9_1;
+
+ AcquireResult updateResponse =
+ HttpMessage.send(urlString, txProvider.getTranslationService(),
+ CoreTranslatorId.BRANCH_CACHE_STORE_REQUEST, message, null);
+ if (!updateResponse.wasSuccessful()) {
+ OseeLog.log(Activator.class, Level.SEVERE, "Error relaying branch updates to servers");
+ }
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, "Error relaying branch updates to servers", ex);
+ } catch (UnsupportedEncodingException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, "Error relaying branch updates to servers", ex);
+ }
+ }
+ }
+ }
+ };
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseArtifactTypeAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseArtifactTypeAccessor.java new file mode 100644 index 00000000000..45610d3c48c --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseArtifactTypeAccessor.java @@ -0,0 +1,265 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.exception.OseeInvalidInheritanceException;
+import org.eclipse.osee.framework.core.model.AbstractOseeType;
+import org.eclipse.osee.framework.core.model.Branch;
+import org.eclipse.osee.framework.core.model.cache.ArtifactTypeCache;
+import org.eclipse.osee.framework.core.model.cache.AttributeTypeCache;
+import org.eclipse.osee.framework.core.model.cache.BranchCache;
+import org.eclipse.osee.framework.core.model.cache.IOseeCache;
+import org.eclipse.osee.framework.core.model.type.ArtifactType;
+import org.eclipse.osee.framework.core.model.type.ArtifactTypeFactory;
+import org.eclipse.osee.framework.core.model.type.AttributeType;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.jdk.core.type.CompositeKeyHashMap;
+import org.eclipse.osee.framework.jdk.core.type.HashCollection;
+import org.eclipse.osee.framework.jdk.core.type.Pair;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseArtifactTypeAccessor extends AbstractDatabaseAccessor<ArtifactType> {
+ protected static final int ABSTRACT_TYPE_INDICATOR = 1;
+ protected static final int CONCRETE_TYPE_INDICATOR = 0;
+
+ private static final String SELECT_ARTIFACT_TYPES = "select * from osee_artifact_type";
+ private static final String INSERT_ARTIFACT_TYPE =
+ "insert into osee_artifact_type (art_type_id, art_type_guid, name, is_abstract) VALUES (?,?,?,?)";
+
+ private static final String UPDATE_ARTIFACT_TYPE =
+ "update osee_artifact_type SET name = ?, is_abstract = ? where art_type_id = ?";
+
+ private static final String SELECT_ARTIFACT_TYPE_INHERITANCE =
+ "select * from osee_artifact_type_inheritance order by super_art_type_id, art_type_id";
+ private static final String INSERT_ARTIFACT_TYPE_INHERITANCE =
+ "insert into osee_artifact_type_inheritance (art_type_id, super_art_type_id) VALUES (?,?)";
+ private static final String DELETE_ARTIFACT_TYPE_INHERITANCE =
+ "delete from osee_artifact_type_inheritance where art_type_id = ?";
+
+ private static final String SELECT_ARTIFACT_TYPE_ATTRIBUTES =
+ "select * from osee_artifact_type_attributes order by art_type_id, branch_id, attr_type_id";
+ private static final String INSERT_ARTIFACT_TYPE_ATTRIBUTES =
+ "insert into osee_artifact_type_attributes (art_type_id, attr_type_id, branch_id) VALUES (?, ?, ?)";
+ private static final String DELETE_ARTIFACT_TYPE_ATTRIBUTES =
+ "delete from osee_artifact_type_attributes where art_type_id = ?";
+
+ private final AttributeTypeCache attributeCache;
+ private final BranchCache branchCache;
+
+ public DatabaseArtifactTypeAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider, BranchCache branchCache, AttributeTypeCache attributeCache) {
+ super(databaseProvider, factoryProvider);
+ this.attributeCache = attributeCache;
+ this.branchCache = branchCache;
+ }
+
+ @Override
+ public void load(IOseeCache<ArtifactType> cache) throws OseeCoreException {
+ attributeCache.ensurePopulated();
+ Set<ArtifactType> loadedTypes = new HashSet<ArtifactType>();
+ ArtifactTypeCache artCache = (ArtifactTypeCache) cache;
+ loadArtifactTypes(artCache, loadedTypes);
+ loadTypeInheritance(artCache);
+ loadAllTypeValidity(artCache);
+ for (ArtifactType type : loadedTypes) {
+ type.clearDirty();
+ }
+ }
+
+ private void loadArtifactTypes(ArtifactTypeCache cache, Set<ArtifactType> loadedTypes) throws OseeCoreException {
+ ArtifactTypeFactory factory = getFactoryService().getArtifactTypeFactory();
+
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(SELECT_ARTIFACT_TYPES);
+
+ while (chStmt.next()) {
+ try {
+ int artTypeId = chStmt.getInt("art_type_id");
+ boolean isAbstract = chStmt.getInt("is_abstract") == ABSTRACT_TYPE_INDICATOR;
+ String artifactTypeName = chStmt.getString("name");
+ String guid = chStmt.getString("art_type_guid");
+
+ ArtifactType artifactType =
+ factory.createOrUpdate(cache, artTypeId, StorageState.LOADED, guid, isAbstract, artifactTypeName);
+ loadedTypes.add(artifactType);
+ } catch (OseeDataStoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ private void loadTypeInheritance(ArtifactTypeCache cache) throws OseeCoreException {
+ IOseeStatement chStmt2 = getDatabaseService().getStatement();
+ try {
+ chStmt2.runPreparedQuery(SELECT_ARTIFACT_TYPE_INHERITANCE);
+ HashCollection<ArtifactType, ArtifactType> baseToSuperTypes =
+ new HashCollection<ArtifactType, ArtifactType>(false, HashSet.class);
+
+ while (chStmt2.next()) {
+ int artTypeId = chStmt2.getInt("art_type_id");
+ int superArtTypeId = chStmt2.getInt("super_art_type_id");
+ ArtifactType baseArtType = cache.getById(artTypeId);
+ ArtifactType superArtType = cache.getById(superArtTypeId);
+
+ if (baseArtType == null) {
+ throw new OseeInvalidInheritanceException(String.format(
+ "ArtifactType [%s] which inherits from [%s] is null", artTypeId, superArtType));
+ }
+ if (superArtType == null) {
+ throw new OseeInvalidInheritanceException(String.format(
+ "ArtifactType [%s] which inherits from null artifact [%s]", artTypeId, superArtType));
+ }
+ baseToSuperTypes.put(baseArtType, superArtType);
+ }
+ for (ArtifactType artifactType : baseToSuperTypes.keySet()) {
+ Set<ArtifactType> superTypes = (Set<ArtifactType>) baseToSuperTypes.getValues(artifactType);
+ if (superTypes != null) {
+ artifactType.setSuperTypes(superTypes);
+ }
+ }
+ } finally {
+ chStmt2.close();
+ }
+ }
+
+ private void loadAllTypeValidity(ArtifactTypeCache cache) throws OseeCoreException {
+ CompositeKeyHashMap<ArtifactType, Branch, Collection<AttributeType>> typeValidity =
+ new CompositeKeyHashMap<ArtifactType, Branch, Collection<AttributeType>>();
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(2000, SELECT_ARTIFACT_TYPE_ATTRIBUTES);
+ while (chStmt.next()) {
+ try {
+ ArtifactType artifactType = cache.getById(chStmt.getInt("art_type_id"));
+ Branch branch = branchCache.getById(chStmt.getInt("branch_id"));
+ AttributeType attributeType = attributeCache.getById(chStmt.getInt("attr_type_id"));
+ Collection<AttributeType> attributes = typeValidity.get(artifactType, branch);
+ if (attributes == null) {
+ attributes = new HashSet<AttributeType>();
+ typeValidity.put(artifactType, branch, attributes);
+ }
+ attributes.add(attributeType);
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ for (Entry<Pair<ArtifactType, Branch>, Collection<AttributeType>> entry : typeValidity.entrySet()) {
+ try {
+ Pair<ArtifactType, Branch> key = entry.getKey();
+ key.getFirst().setAttributeTypes(entry.getValue(), key.getSecond());
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ }
+
+ @Override
+ public void store(Collection<ArtifactType> types) throws OseeCoreException {
+ Set<ArtifactType> typeInheritanceChanges = new HashSet<ArtifactType>();
+ Set<ArtifactType> typeValidityChanges = new HashSet<ArtifactType>();
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> updateData = new ArrayList<Object[]>();
+
+ for (ArtifactType type : types) {
+ if (isDataDirty(type)) {
+ int abstractValue = type.isAbstract() ? ABSTRACT_TYPE_INDICATOR : CONCRETE_TYPE_INDICATOR;
+ switch (type.getStorageState()) {
+ case CREATED:
+ type.setId(getSequence().getNextArtifactTypeId());
+ insertData.add(new Object[] {type.getId(), type.getGuid(), type.getName(), abstractValue});
+ break;
+ case MODIFIED:
+ updateData.add(new Object[] {type.getName(), abstractValue, type.getId()});
+ break;
+ default:
+ break;
+ }
+ }
+ if (type.isFieldDirty(ArtifactType.ARTIFACT_INHERITANCE_FIELD_KEY)) {
+ typeInheritanceChanges.add(type);
+
+ }
+ if (type.isFieldDirty(ArtifactType.ARTIFACT_TYPE_ATTRIBUTES_FIELD_KEY)) {
+ typeValidityChanges.add(type);
+ }
+ }
+ getDatabaseService().runBatchUpdate(INSERT_ARTIFACT_TYPE, insertData);
+ getDatabaseService().runBatchUpdate(UPDATE_ARTIFACT_TYPE, updateData);
+
+ storeArtifactTypeInheritance(typeInheritanceChanges);
+ storeAttributeTypeValidity(types);
+
+ for (ArtifactType type : types) {
+ type.clearDirty();
+ }
+ }
+
+ private boolean isDataDirty(ArtifactType type) throws OseeCoreException {
+ return type.areFieldsDirty(AbstractOseeType.NAME_FIELD_KEY, AbstractOseeType.UNIQUE_ID_FIELD_KEY,
+ ArtifactType.ARTIFACT_IS_ABSTRACT_FIELD_KEY);
+ }
+
+ private void storeArtifactTypeInheritance(Collection<ArtifactType> types) throws OseeDataStoreException {
+ List<Object[]> insertInheritanceData = new ArrayList<Object[]>();
+ List<Object[]> deleteInheritanceData = new ArrayList<Object[]>();
+ for (ArtifactType type : types) {
+ deleteInheritanceData.add(new Object[] {type.getId()});
+ for (ArtifactType superType : type.getSuperArtifactTypes()) {
+ insertInheritanceData.add(new Object[] {type.getId(), superType.getId()});
+ }
+ }
+ getDatabaseService().runBatchUpdate(DELETE_ARTIFACT_TYPE_INHERITANCE, deleteInheritanceData);
+ getDatabaseService().runBatchUpdate(INSERT_ARTIFACT_TYPE_INHERITANCE, insertInheritanceData);
+ }
+
+ private void storeAttributeTypeValidity(Collection<ArtifactType> types) throws OseeCoreException {
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> deleteData = new ArrayList<Object[]>();
+ for (ArtifactType artifactType : types) {
+ deleteData.add(new Object[] {artifactType.getId()});
+ Map<Branch, Collection<AttributeType>> entries = artifactType.getLocalAttributeTypes();
+ if (entries != null) {
+ for (Entry<Branch, Collection<AttributeType>> entry : entries.entrySet()) {
+ Branch branch = entry.getKey();
+ for (AttributeType attributeType : entry.getValue()) {
+ insertData.add(new Object[] {artifactType.getId(), attributeType.getId(), branch.getId()});
+ }
+ }
+ }
+ }
+ getDatabaseService().runBatchUpdate(DELETE_ARTIFACT_TYPE_ATTRIBUTES, deleteData);
+ getDatabaseService().runBatchUpdate(INSERT_ARTIFACT_TYPE_ATTRIBUTES, insertData);
+ }
+
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseAttributeTypeAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseAttributeTypeAccessor.java new file mode 100644 index 00000000000..12219ca47ff --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseAttributeTypeAccessor.java @@ -0,0 +1,189 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.model.cache.IOseeCache;
+import org.eclipse.osee.framework.core.model.cache.OseeEnumTypeCache;
+import org.eclipse.osee.framework.core.model.type.AttributeType;
+import org.eclipse.osee.framework.core.model.type.AttributeTypeFactory;
+import org.eclipse.osee.framework.core.model.type.OseeEnumType;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.database.core.SQL3DataType;
+import org.eclipse.osee.framework.jdk.core.util.Strings;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseAttributeTypeAccessor extends AbstractDatabaseAccessor<AttributeType> {
+
+ private static final String SELECT_ATTRIBUTE_TYPES =
+ "SELECT * FROM osee_attribute_type aty1, osee_attribute_base_type aby1, osee_attribute_provider_type apy1 WHERE aty1.attr_base_type_id = aby1.attr_base_type_id AND aty1.attr_provider_type_id = apy1.attr_provider_type_id";
+ private static final String INSERT_ATTRIBUTE_TYPE =
+ "INSERT INTO osee_attribute_type (attr_type_id, attr_type_guid, attr_base_type_id, attr_provider_type_id, file_type_extension, name, default_value, enum_type_id, min_occurence, max_occurence, tip_text, tagger_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
+ private static final String UPDATE_ATTRIBUTE_TYPE =
+ "update osee_attribute_type SET attr_base_type_id=?, attr_provider_type_id=?, file_type_extension=?, name=?, default_value=?, enum_type_id=?, min_occurence=?, max_occurence=?, tip_text=?, tagger_id=? where attr_type_id = ?";
+
+ private static final String INSERT_BASE_ATTRIBUTE_TYPE =
+ "INSERT INTO osee_attribute_base_type (attr_base_type_id, attribute_class) VALUES (?, ?)";
+ private static final String INSERT_ATTRIBUTE_PROVIDER_TYPE =
+ "INSERT INTO osee_attribute_provider_type (attr_provider_type_id, attribute_provider_class) VALUES (?, ?)";
+ private static final String SELECT_ATTRIBUTE_BASE_TYPE =
+ "SELECT attr_base_type_id FROM osee_attribute_base_type WHERE attribute_class = ?";
+ private static final String SELECT_ATTRIBUTE_PROVIDER_TYPE =
+ "SELECT attr_provider_type_id FROM osee_attribute_provider_type WHERE attribute_provider_class = ?";
+
+ private final OseeEnumTypeCache enumCache;
+
+ public DatabaseAttributeTypeAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider, OseeEnumTypeCache enumCache) {
+ super(databaseProvider, factoryProvider);
+ this.enumCache = enumCache;
+ }
+
+ @Override
+ public void load(IOseeCache<AttributeType> cache) throws OseeCoreException {
+ enumCache.ensurePopulated();
+
+ AttributeTypeFactory factory = getFactoryService().getAttributeTypeFactory();
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+
+ try {
+ chStmt.runPreparedQuery(SELECT_ATTRIBUTE_TYPES);
+
+ while (chStmt.next()) {
+ int attributeTypeId = chStmt.getInt("attr_type_id");
+ String baseAttributeTypeId = Strings.intern(chStmt.getString("attribute_class"));
+ String attributeProviderNameId = Strings.intern(chStmt.getString("attribute_provider_class"));
+ try {
+ String guid = chStmt.getString("attr_type_guid");
+ String typeName = chStmt.getString("name");
+ String fileTypeExtension = Strings.intern(chStmt.getString("file_type_extension"));
+ String defaultValue = chStmt.getString("default_value");
+ int minOccurrences = chStmt.getInt("min_occurence");
+ int maxOccurrences = chStmt.getInt("max_occurence");
+ String description = chStmt.getString("tip_text");
+ String taggerId = Strings.intern(chStmt.getString("tagger_id"));
+
+ int enumTypeId = chStmt.getInt("enum_type_id");
+ OseeEnumType oseeEnumType = enumCache.getById(enumTypeId);
+
+ AttributeType attributeType =
+ factory.createOrUpdate(cache, attributeTypeId, StorageState.LOADED, guid, typeName,
+ baseAttributeTypeId, attributeProviderNameId, fileTypeExtension, defaultValue, oseeEnumType,
+ minOccurrences, maxOccurrences, description, taggerId);
+
+ attributeType.clearDirty();
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ @Override
+ public void store(Collection<AttributeType> types) throws OseeCoreException {
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> updateData = new ArrayList<Object[]>();
+ for (AttributeType type : types) {
+ if (type.isDirty()) {
+ switch (type.getStorageState()) {
+ case CREATED:
+ type.setId(getSequence().getNextAttributeTypeId());
+ insertData.add(toInsertValues(type));
+ break;
+ case MODIFIED:
+ updateData.add(toUpdateValues(type));
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ getDatabaseService().runBatchUpdate(INSERT_ATTRIBUTE_TYPE, insertData);
+ getDatabaseService().runBatchUpdate(UPDATE_ATTRIBUTE_TYPE, updateData);
+ for (AttributeType type : types) {
+ type.clearDirty();
+ }
+ }
+
+ private Object[] toInsertValues(AttributeType type) throws OseeDataStoreException {
+ int attrBaseTypeId = getOrCreateAttributeBaseType(type.getBaseAttributeTypeId());
+ int attrProviderTypeId = getOrCreateAttributeProviderType(type.getAttributeProviderId());
+ return new Object[] {type.getId(), type.getGuid(), attrBaseTypeId, attrProviderTypeId,
+ type.getFileTypeExtension() == null ? SQL3DataType.VARCHAR : type.getFileTypeExtension(),
+ type.getName() == null ? SQL3DataType.VARCHAR : type.getName(),
+ type.getDefaultValue() == null ? SQL3DataType.VARCHAR : type.getDefaultValue(), type.getOseeEnumTypeId(),
+ type.getMinOccurrences(), type.getMaxOccurrences(),
+ type.getDescription() == null ? SQL3DataType.VARCHAR : type.getDescription(),
+ type.getTaggerId() == null ? SQL3DataType.VARCHAR : type.getTaggerId()};
+ }
+
+ private Object[] toUpdateValues(AttributeType type) throws OseeDataStoreException {
+ int attrBaseTypeId = getOrCreateAttributeBaseType(type.getBaseAttributeTypeId());
+ int attrProviderTypeId = getOrCreateAttributeProviderType(type.getAttributeProviderId());
+ return new Object[] {attrBaseTypeId, attrProviderTypeId,
+ type.getFileTypeExtension() == null ? SQL3DataType.VARCHAR : type.getFileTypeExtension(),
+ type.getName() == null ? SQL3DataType.VARCHAR : type.getName(),
+ type.getDefaultValue() == null ? SQL3DataType.VARCHAR : type.getDefaultValue(), type.getOseeEnumTypeId(),
+ type.getMinOccurrences(), type.getMaxOccurrences(),
+ type.getDescription() == null ? SQL3DataType.VARCHAR : type.getDescription(),
+ type.getTaggerId() == null ? SQL3DataType.VARCHAR : type.getTaggerId(), type.getId()};
+ }
+
+ @SuppressWarnings("unchecked")
+ private int getOrCreateAttributeProviderType(String attrProviderExtension) throws OseeDataStoreException {
+ int attrBaseTypeId = -1;
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(SELECT_ATTRIBUTE_PROVIDER_TYPE, attrProviderExtension);
+ if (chStmt.next()) {
+ attrBaseTypeId = chStmt.getInt("attr_provider_type_id");
+ } else {
+ attrBaseTypeId = getSequence().getNextAttributeProviderTypeId();
+ getDatabaseService().runPreparedUpdate(INSERT_ATTRIBUTE_PROVIDER_TYPE, attrBaseTypeId,
+ attrProviderExtension);
+ }
+ } finally {
+ chStmt.close();
+ }
+ return attrBaseTypeId;
+ }
+
+ @SuppressWarnings("unchecked")
+ private int getOrCreateAttributeBaseType(String attrBaseExtension) throws OseeDataStoreException {
+ int attrBaseTypeId = -1;
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(SELECT_ATTRIBUTE_BASE_TYPE, attrBaseExtension);
+ if (chStmt.next()) {
+ attrBaseTypeId = chStmt.getInt("attr_base_type_id");
+ } else {
+ attrBaseTypeId = getSequence().getNextAttributeBaseTypeId();
+ getDatabaseService().runPreparedUpdate(INSERT_BASE_ATTRIBUTE_TYPE, attrBaseTypeId, attrBaseExtension);
+ }
+ } finally {
+ chStmt.close();
+ }
+ return attrBaseTypeId;
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseBranchAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseBranchAccessor.java new file mode 100644 index 00000000000..1ad30fd6aac --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseBranchAccessor.java @@ -0,0 +1,183 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+import java.util.logging.Level;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.BranchArchivedState;
+import org.eclipse.osee.framework.core.enums.BranchState;
+import org.eclipse.osee.framework.core.enums.BranchType;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.BranchDoesNotExist;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.model.Branch;
+import org.eclipse.osee.framework.core.model.BranchFactory;
+import org.eclipse.osee.framework.core.model.DefaultBasicArtifact;
+import org.eclipse.osee.framework.core.model.MergeBranch;
+import org.eclipse.osee.framework.core.model.TransactionRecord;
+import org.eclipse.osee.framework.core.model.cache.BranchCache;
+import org.eclipse.osee.framework.core.model.cache.IOseeCache;
+import org.eclipse.osee.framework.core.model.cache.TransactionCache;
+import org.eclipse.osee.framework.core.operation.Operations;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.jdk.core.util.Lib;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseBranchAccessor extends AbstractDatabaseAccessor<Branch> {
+
+ private static final String SELECT_BRANCHES = "SELECT * FROM osee_branch";
+ private static final String SELECT_MERGE_BRANCHES = "SELECT * FROM osee_merge";
+
+ private final TransactionCache txCache;
+ private final IBranchUpdateEvent eventSender;
+
+ public DatabaseBranchAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider, IBranchUpdateEvent eventSender, TransactionCache txCache) {
+ super(databaseProvider, factoryProvider);
+ this.txCache = txCache;
+ this.eventSender = eventSender;
+ }
+
+ @Override
+ public void load(IOseeCache<Branch> cache) throws OseeCoreException {
+ long startTime = System.currentTimeMillis();
+ Map<Branch, Integer> childToParent = new HashMap<Branch, Integer>();
+ Map<Branch, Integer> branchToBaseTx = new HashMap<Branch, Integer>();
+ Map<Branch, Integer> branchToSourceTx = new HashMap<Branch, Integer>();
+ Map<Branch, Integer> associatedArtifact = new HashMap<Branch, Integer>();
+
+ BranchCache brCache = (BranchCache) cache;
+ loadBranches(brCache, childToParent, branchToBaseTx, branchToSourceTx, associatedArtifact);
+ loadBranchHierarchy(brCache, childToParent);
+ loadMergeBranches(brCache);
+ loadAssociatedArtifacts(brCache, associatedArtifact);
+ loadBranchRelatedTransactions(brCache, branchToBaseTx, branchToSourceTx);
+
+ for (Branch branch : cache.getAll()) {
+ branch.clearDirty();
+ }
+ OseeLog.log(Activator.class, Level.INFO,
+ String.format("Branch Cache loaded [%s]", Lib.getElapseString(startTime)));
+ }
+
+ private void loadBranches(BranchCache cache, Map<Branch, Integer> childToParent, Map<Branch, Integer> branchToBaseTx, Map<Branch, Integer> branchToSourceTx, Map<Branch, Integer> associatedArtifact) throws OseeCoreException {
+ BranchFactory factory = getFactoryService().getBranchFactory();
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(2000, SELECT_BRANCHES);
+ while (chStmt.next()) {
+ try {
+ int branchId = chStmt.getInt("branch_id");
+
+ String branchName = chStmt.getString("branch_name");
+ BranchState branchState = BranchState.getBranchState(chStmt.getInt("branch_state"));
+ BranchType branchType = BranchType.valueOf(chStmt.getInt("branch_type"));
+ boolean isArchived = BranchArchivedState.valueOf(chStmt.getInt("archived")).isArchived();
+ String branchGuid = chStmt.getString("branch_guid");
+ Branch branch =
+ factory.createOrUpdate(cache, branchId, StorageState.LOADED, branchGuid, branchName, branchType,
+ branchState, isArchived);
+
+ Integer parentBranchId = chStmt.getInt("parent_branch_id");
+ if (parentBranchId != BranchStoreOperation.NULL_PARENT_BRANCH_ID) {
+ childToParent.put(branch, parentBranchId);
+ }
+ branchToSourceTx.put(branch, chStmt.getInt("parent_transaction_id"));
+ branchToBaseTx.put(branch, chStmt.getInt("baseline_transaction_id"));
+ associatedArtifact.put(branch, chStmt.getInt("associated_art_id"));
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ private void loadAssociatedArtifacts(BranchCache cache, Map<Branch, Integer> associatedArtifact) throws OseeCoreException {
+ for (Entry<Branch, Integer> entry : associatedArtifact.entrySet()) {
+ Branch branch = entry.getKey();
+ branch.setAssociatedArtifact(new DefaultBasicArtifact(entry.getValue(), null, null));
+ }
+ }
+
+ private void loadBranchRelatedTransactions(BranchCache cache, Map<Branch, Integer> branchToBaseTx, Map<Branch, Integer> branchToSourceTx) throws OseeCoreException {
+ Set<Integer> transactionIds = new HashSet<Integer>();
+ transactionIds.addAll(branchToSourceTx.values());
+ transactionIds.addAll(branchToBaseTx.values());
+ txCache.loadTransactions(transactionIds);
+
+ for (Entry<Branch, Integer> entry : branchToBaseTx.entrySet()) {
+ Branch branch = entry.getKey();
+ if (branch.getBaseTransaction() == null) {
+ TransactionRecord baseTx = txCache.getById(entry.getValue());
+ branch.setBaseTransaction(baseTx);
+ }
+ }
+
+ for (Entry<Branch, Integer> entry : branchToSourceTx.entrySet()) {
+ Branch branch = entry.getKey();
+ if (branch.getSourceTransaction() == null) {
+ TransactionRecord srcTx = txCache.getById(entry.getValue());
+ branch.setSourceTransaction(srcTx);
+ }
+ }
+ }
+
+ private void loadBranchHierarchy(BranchCache branchCache, Map<Branch, Integer> childToParent) throws OseeCoreException {
+ for (Entry<Branch, Integer> entry : childToParent.entrySet()) {
+ Branch childBranch = entry.getKey();
+ Branch parentBranch = branchCache.getById(entry.getValue());
+ if (parentBranch == null) {
+ throw new BranchDoesNotExist(String.format("Parent Branch id:[%s] does not exist for child branch [%s]",
+ entry.getValue(), entry.getKey()));
+ }
+ childBranch.setParentBranch(parentBranch);
+ }
+ }
+
+ private void loadMergeBranches(BranchCache branchCache) throws OseeCoreException {
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(1000, SELECT_MERGE_BRANCHES);
+ while (chStmt.next()) {
+ Branch sourceBranch = branchCache.getById(chStmt.getInt("source_branch_id"));
+ Branch destBranch = branchCache.getById(chStmt.getInt("dest_branch_id"));
+
+ MergeBranch mergeBranch = (MergeBranch) branchCache.getById(chStmt.getInt("merge_branch_id"));
+ mergeBranch.setSourceBranch(sourceBranch);
+ mergeBranch.setDestinationBranch(destBranch);
+ }
+ } finally {
+ chStmt.close();
+ }
+
+ }
+
+ @Override
+ public void store(Collection<Branch> branches) throws OseeCoreException {
+ Operations.executeWorkAndCheckStatus(
+ new BranchStoreOperation(getDatabaseServiceProvider(), eventSender, branches), new NullProgressMonitor(),
+ -1);
+ }
+
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseOseeEnumTypeAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseOseeEnumTypeAccessor.java new file mode 100644 index 00000000000..54365cf1ef1 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseOseeEnumTypeAccessor.java @@ -0,0 +1,198 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.model.AbstractOseeType;
+import org.eclipse.osee.framework.core.model.OseeEnumEntry;
+import org.eclipse.osee.framework.core.model.cache.IOseeCache;
+import org.eclipse.osee.framework.core.model.type.OseeEnumType;
+import org.eclipse.osee.framework.core.model.type.OseeEnumTypeFactory;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.jdk.core.type.HashCollection;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseOseeEnumTypeAccessor extends AbstractDatabaseAccessor<OseeEnumType> {
+
+ private static final String SELECT_OSEE_ENUM_TYPES = "select * from osee_enum_type oet";
+ private static final String SELECT_OSEE_ENUM_ENTRIES =
+ "select * from osee_enum_type_def order by enum_type_id, ordinal";
+
+ private static final String INSERT_ENUM_TYPE =
+ "insert into osee_enum_type (enum_type_id, enum_type_guid, enum_type_name) values (?,?,?)";
+ private static final String UPDATE_ENUM_TYPE = "update osee_enum_type set enum_type_name=? where enum_type_id=?";
+ private static final String DELETE_ENUM_TYPE = "delete from osee_enum_type oet where enum_type_id = ?";
+
+ private static final String INSERT_ENUM_TYPE_DEF =
+ "insert into osee_enum_type_def (enum_type_id, enum_entry_guid, name, ordinal) values (?,?,?,?)";
+ private static final String DELETE_ENUM_TYPE_DEF = "delete from osee_enum_type_def where enum_type_id = ?";
+
+ public DatabaseOseeEnumTypeAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider) {
+ super(databaseProvider, factoryProvider);
+ }
+
+ private void loadEnumEntries(OseeEnumTypeFactory factory, HashCollection<Integer, OseeEnumEntry> entryTypes) throws OseeCoreException {
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(SELECT_OSEE_ENUM_ENTRIES);
+ while (chStmt.next()) {
+ try {
+ Integer enumTypeId = chStmt.getInt("enum_type_id");
+ String enumEntryGuid = chStmt.getString("enum_entry_guid");
+ String enumEntryName = chStmt.getString("name");
+ int ordinal = chStmt.getInt("ordinal");
+
+ OseeEnumEntry entry = factory.createEnumEntry(enumEntryGuid, enumEntryName, ordinal);
+ entry.setStorageState(StorageState.LOADED);
+ entry.clearDirty();
+ entryTypes.put(enumTypeId, entry);
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ @Override
+ public void load(IOseeCache<OseeEnumType> cache) throws OseeCoreException {
+ OseeEnumTypeFactory factory = getFactoryService().getOseeEnumTypeFactory();
+
+ HashCollection<Integer, OseeEnumEntry> entryTypes = new HashCollection<Integer, OseeEnumEntry>();
+
+ loadEnumEntries(factory, entryTypes);
+
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+ try {
+ chStmt.runPreparedQuery(SELECT_OSEE_ENUM_TYPES);
+ while (chStmt.next()) {
+ try {
+ Integer enumTypeId = chStmt.getInt("enum_type_id");
+ String enumTypeGuid = chStmt.getString("enum_type_guid");
+ String enumTypeName = chStmt.getString("enum_type_name");
+
+ OseeEnumType oseeEnumType =
+ factory.createOrUpdate(cache, enumTypeId, StorageState.LOADED, enumTypeGuid, enumTypeName);
+
+ List<OseeEnumEntry> oseeEnumEntries = (List<OseeEnumEntry>) entryTypes.getValues(enumTypeId);
+ if (oseeEnumEntries != null) {
+ oseeEnumType.setEntries(oseeEnumEntries);
+ oseeEnumType.clearDirty();
+ }
+ } catch (OseeCoreException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ @Override
+ public void store(Collection<OseeEnumType> oseeEnumTypes) throws OseeCoreException {
+ Set<OseeEnumType> dirtyEntries = new HashSet<OseeEnumType>();
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> updateData = new ArrayList<Object[]>();
+ List<Object[]> deleteData = new ArrayList<Object[]>();
+ for (OseeEnumType oseeEnumType : oseeEnumTypes) {
+ if (isDataDirty(oseeEnumType)) {
+ switch (oseeEnumType.getStorageState()) {
+ case CREATED:
+ oseeEnumType.setId(getSequence().getNextOseeEnumTypeId());
+ insertData.add(toInsertValues(oseeEnumType));
+ break;
+ case MODIFIED:
+ updateData.add(toUpdateValues(oseeEnumType));
+ break;
+ case PURGED:
+ deleteData.add(toDeleteValues(oseeEnumType));
+ break;
+ default:
+ break;
+ }
+ }
+ if (oseeEnumType.isFieldDirty(OseeEnumType.OSEE_ENUM_TYPE_ENTRIES_FIELD)) {
+ dirtyEntries.add(oseeEnumType);
+ }
+ }
+ getDatabaseService().runBatchUpdate(INSERT_ENUM_TYPE, insertData);
+ getDatabaseService().runBatchUpdate(UPDATE_ENUM_TYPE, updateData);
+ getDatabaseService().runBatchUpdate(DELETE_ENUM_TYPE, deleteData);
+
+ storeOseeEnumEntries(dirtyEntries);
+ for (OseeEnumType oseeEnumType : oseeEnumTypes) {
+ oseeEnumType.clearDirty();
+ for (OseeEnumEntry entry : oseeEnumType.values()) {
+ entry.clearDirty();
+ }
+ }
+ }
+
+ private boolean isDataDirty(OseeEnumType type) throws OseeCoreException {
+ return type.areFieldsDirty(AbstractOseeType.NAME_FIELD_KEY, AbstractOseeType.UNIQUE_ID_FIELD_KEY);
+ }
+
+ private void storeOseeEnumEntries(Collection<OseeEnumType> oseeEnumTypes) throws OseeCoreException {
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> deleteData = new ArrayList<Object[]>();
+
+ for (OseeEnumType type : oseeEnumTypes) {
+ // Delete all type entries that have been inserted into the DB before
+ if (type.isIdValid()) {
+ deleteData.add(toDeleteValues(type));
+ }
+
+ //Re-add only entries that are valid
+ for (OseeEnumEntry entry : type.values()) {
+ if (StorageState.PURGED != entry.getStorageState()) {
+ if (!entry.isIdValid()) {
+ entry.setId(type.getId());
+ }
+ insertData.add(toInsertValues(entry));
+ }
+ }
+ }
+
+ getDatabaseService().runBatchUpdate(DELETE_ENUM_TYPE_DEF, deleteData);
+ getDatabaseService().runBatchUpdate(INSERT_ENUM_TYPE_DEF, insertData);
+ }
+
+ private Object[] toInsertValues(OseeEnumType type) throws OseeDataStoreException {
+ return new Object[] {type.getId(), type.getGuid(), type.getName()};
+ }
+
+ private Object[] toUpdateValues(OseeEnumType type) throws OseeDataStoreException {
+ return new Object[] {type.getName(), type.getId()};
+ }
+
+ private Object[] toDeleteValues(OseeEnumType type) throws OseeDataStoreException {
+ return new Object[] {type.getId()};
+ }
+
+ private Object[] toInsertValues(OseeEnumEntry type) throws OseeDataStoreException {
+ return new Object[] {type.getId(), type.getGuid(), type.getName(), type.ordinal()};
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseRelationTypeAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseRelationTypeAccessor.java new file mode 100644 index 00000000000..c9501916046 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseRelationTypeAccessor.java @@ -0,0 +1,134 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.enums.RelationTypeMultiplicity;
+import org.eclipse.osee.framework.core.enums.StorageState;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.model.cache.ArtifactTypeCache;
+import org.eclipse.osee.framework.core.model.cache.IOseeCache;
+import org.eclipse.osee.framework.core.model.type.ArtifactType;
+import org.eclipse.osee.framework.core.model.type.RelationType;
+import org.eclipse.osee.framework.core.model.type.RelationTypeFactory;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.database.core.OseeConnection;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseRelationTypeAccessor extends AbstractDatabaseAccessor<RelationType> {
+ private static final String SELECT_LINK_TYPES = "SELECT * FROM osee_relation_link_type";
+ private static final String INSERT_RELATION_TYPE =
+ "INSERT INTO osee_relation_link_type (rel_link_type_id, rel_link_type_guid, type_name, a_name, b_name, a_art_type_id, b_art_type_id, multiplicity, default_order_type_guid) VALUES (?,?,?,?,?,?,?,?,?)";
+ private static final String UPDATE_RELATION_TYPE =
+ "update osee_relation_link_type SET type_name=?, a_name=?, b_name=?, a_art_type_id=?, b_art_type_id=?, multiplicity=?, default_order_type_guid=? where rel_link_type_id = ?";
+
+ private final ArtifactTypeCache artifactCache;
+
+ public DatabaseRelationTypeAccessor(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider, ArtifactTypeCache artifactCache) {
+ super(databaseProvider, factoryProvider);
+ this.artifactCache = artifactCache;
+ }
+
+ @Override
+ public void load(IOseeCache<RelationType> cache) throws OseeCoreException {
+ artifactCache.ensurePopulated();
+ RelationTypeFactory factory = getFactoryService().getRelationTypeFactory();
+ IOseeStatement chStmt = getDatabaseService().getStatement();
+
+ try {
+ chStmt.runPreparedQuery(SELECT_LINK_TYPES);
+
+ while (chStmt.next()) {
+ String typeName = chStmt.getString("type_name");
+ int typeId = chStmt.getInt("rel_link_type_id");
+ int aArtTypeId = chStmt.getInt("a_art_type_id");
+ int bArtTypeId = chStmt.getInt("b_art_type_id");
+ int multiplicityValue = chStmt.getInt("multiplicity");
+ try {
+ ArtifactType artifactTypeSideA = artifactCache.getById(aArtTypeId);
+ ArtifactType artifactTypeSideB = artifactCache.getById(bArtTypeId);
+ RelationTypeMultiplicity multiplicity =
+ RelationTypeMultiplicity.getRelationMultiplicity(multiplicityValue);
+ String sideAName = chStmt.getString("a_name");
+ String sideBName = chStmt.getString("b_name");
+ String defaultOrderTypeGuid = chStmt.getString("default_order_type_guid");
+ String guid = chStmt.getString("rel_link_type_guid");
+
+ RelationType relationType =
+ factory.createOrUpdate(cache, typeId, StorageState.LOADED, guid, typeName, sideAName, sideBName,
+ artifactTypeSideA, artifactTypeSideB, multiplicity, defaultOrderTypeGuid);
+ relationType.clearDirty();
+ } catch (OseeCoreException ex) {
+ String message =
+ String.format(
+ "Error loading relation type - name:[%s] id:[%s] aArtTypeId:[%s] bArtTypeid:[%s] multiplicity:[%s]",
+ typeName, typeId, aArtTypeId, bArtTypeId, multiplicityValue);
+ OseeLog.log(Activator.class, Level.SEVERE, message, ex);
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ }
+
+ @Override
+ public void store(Collection<RelationType> relationTypes) throws OseeCoreException {
+ List<Object[]> insertData = new ArrayList<Object[]>();
+ List<Object[]> updateData = new ArrayList<Object[]>();
+ for (RelationType type : relationTypes) {
+ if (type.isDirty()) {
+ switch (type.getStorageState()) {
+ case CREATED:
+ type.setId(getSequence().getNextRelationTypeId());
+ insertData.add(toInsertValues(type));
+ break;
+ case MODIFIED:
+ updateData.add(toUpdateValues(type));
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ OseeConnection connection = getDatabaseService().getConnection();
+ try {
+ getDatabaseService().runBatchUpdate(connection, INSERT_RELATION_TYPE, insertData);
+ getDatabaseService().runBatchUpdate(connection, UPDATE_RELATION_TYPE, updateData);
+ } finally {
+ connection.close();
+ }
+ for (RelationType type : relationTypes) {
+ type.clearDirty();
+ }
+ }
+
+ private Object[] toInsertValues(RelationType type) throws OseeDataStoreException {
+ return new Object[] {type.getId(), type.getGuid(), type.getName(), type.getSideAName(), type.getSideBName(),
+ type.getArtifactTypeSideA().getId(), type.getArtifactTypeSideB().getId(),
+ type.getMultiplicity().getValue(), type.getDefaultOrderTypeGuid()};
+ }
+
+ private Object[] toUpdateValues(RelationType type) throws OseeDataStoreException {
+ return new Object[] {type.getName(), type.getSideAName(), type.getSideBName(),
+ type.getArtifactTypeSideA().getId(), type.getArtifactTypeSideB().getId(),
+ type.getMultiplicity().getValue(), type.getDefaultOrderTypeGuid(), type.getId()};
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseTransactionRecordAccessor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseTransactionRecordAccessor.java new file mode 100644 index 00000000000..b14d51392d4 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/DatabaseTransactionRecordAccessor.java @@ -0,0 +1,155 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.Collection;
+import java.util.Date;
+import org.eclipse.osee.framework.core.enums.TransactionDetailsType;
+import org.eclipse.osee.framework.core.enums.TransactionVersion;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeStateException;
+import org.eclipse.osee.framework.core.model.Branch;
+import org.eclipse.osee.framework.core.model.TransactionRecord;
+import org.eclipse.osee.framework.core.model.TransactionRecordFactory;
+import org.eclipse.osee.framework.core.model.cache.BranchCache;
+import org.eclipse.osee.framework.core.model.cache.ITransactionDataAccessor;
+import org.eclipse.osee.framework.core.model.cache.TransactionCache;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.IOseeStatement;
+import org.eclipse.osee.framework.database.core.JoinUtility;
+import org.eclipse.osee.framework.database.core.JoinUtility.IdJoinQuery;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseTransactionRecordAccessor implements ITransactionDataAccessor {
+
+ private static final String SELECT_BASE_TRANSACTION =
+ "select txd.* from osee_branch ob, osee_tx_details txd WHERE ob.branch_id = ? AND ob.baseline_transaction_id = txd.transaction_id";
+
+ private static final String SELECT_BY_TRANSACTION = "select * from osee_tx_details WHERE transaction_id = ?";
+
+ private static final String SELECT_BRANCH_TRANSACTIONS =
+ "select * from osee_tx_details where branch_id = ? order by transaction_id DESC";
+
+ private static final String SELECT_TRANSACTIONS_BY_QUERY_ID =
+ "select * from osee_tx_details txd, osee_join_id oji where txd.transaction_id = oji.id and oji.query_id = ?";
+
+ private final IOseeDatabaseServiceProvider oseeDatabaseProvider;
+ private final BranchCache branchCache;
+ private final IOseeModelFactoryServiceProvider factoryProvider;
+
+ public DatabaseTransactionRecordAccessor(IOseeDatabaseServiceProvider oseeDatabaseProvider, IOseeModelFactoryServiceProvider factoryProvider, BranchCache branchCache) {
+ this.oseeDatabaseProvider = oseeDatabaseProvider;
+ this.factoryProvider = factoryProvider;
+ this.branchCache = branchCache;
+ }
+
+ private synchronized void ensureDependantCachePopulated() throws OseeCoreException {
+ branchCache.ensurePopulated();
+ }
+
+ public void loadTransactionRecord(TransactionCache cache, Collection<Integer> transactionIds) throws OseeCoreException {
+ if (transactionIds.isEmpty()) {
+ return;
+ }
+ ensureDependantCachePopulated();
+ if (transactionIds.size() > 1) {
+ IdJoinQuery joinQuery = JoinUtility.createIdJoinQuery();
+ try {
+ for (Integer txNumber : transactionIds) {
+ joinQuery.add(txNumber);
+ }
+ joinQuery.store();
+
+ loadFromTransaction(cache, null, 5000, false, SELECT_TRANSACTIONS_BY_QUERY_ID, joinQuery.getQueryId());
+
+ } finally {
+ joinQuery.delete();
+ }
+ } else {
+ loadFromTransaction(cache, null, 1, SELECT_BY_TRANSACTION, transactionIds.iterator().next());
+ }
+ }
+
+ public void loadTransactionRecord(TransactionCache cache, Branch branch) throws OseeCoreException {
+ ensureDependantCachePopulated();
+ loadFromTransaction(cache, branch, 1000, SELECT_BRANCH_TRANSACTIONS, branch.getId());
+ }
+
+ public TransactionRecord loadTransactionRecord(TransactionCache cache, Branch branch, TransactionVersion transactionType) throws OseeCoreException {
+ ensureDependantCachePopulated();
+ TransactionRecord toReturn = null;
+ switch (transactionType) {
+ case BASE:
+ toReturn = loadFirstTransactionRecord(cache, branch, SELECT_BASE_TRANSACTION, branch.getId());
+ break;
+ case HEAD:
+ toReturn = loadFirstTransactionRecord(cache, branch, SELECT_BRANCH_TRANSACTIONS, branch.getId());
+ break;
+ default:
+ throw new OseeStateException(String.format("Transaction Type [%s] is not supported", transactionType));
+ }
+ return toReturn;
+ }
+
+ private TransactionRecord loadFirstTransactionRecord(TransactionCache cache, Branch branch, String query, Object... parameters) throws OseeCoreException {
+ ensureDependantCachePopulated();
+ return loadFromTransaction(cache, branch, 1, true, query, parameters);
+ }
+
+ private void loadFromTransaction(TransactionCache cache, Branch branch, int fetchSize, String query, Object... parameters) throws OseeCoreException {
+ ensureDependantCachePopulated();
+ loadFromTransaction(cache, branch, fetchSize, false, query, parameters);
+ }
+
+ private TransactionRecord loadFromTransaction(TransactionCache cache, Branch branch, int fetchSize, boolean isOnlyReadFirstResult, String query, Object... parameters) throws OseeCoreException {
+ IOseeStatement chStmt = oseeDatabaseProvider.getOseeDatabaseService().getStatement();
+ TransactionRecord record = null;
+ try {
+ chStmt.runPreparedQuery(fetchSize, query, parameters);
+ while (chStmt.next()) {
+ int branchId = chStmt.getInt("branch_id");
+ int transactionNumber = chStmt.getInt("transaction_id");
+ String comment = chStmt.getString("osee_comment");
+ Date timestamp = chStmt.getTimestamp("time");
+ int authorArtId = chStmt.getInt("author");
+ int commitArtId = chStmt.getInt("commit_art_id");
+ TransactionDetailsType txType = TransactionDetailsType.toEnum(chStmt.getInt("tx_type"));
+
+ record =
+ prepareTransactionRecord(cache, transactionNumber, branchId, comment, timestamp, authorArtId,
+ commitArtId, txType);
+ if (isOnlyReadFirstResult) {
+ break;
+ }
+ }
+ } finally {
+ chStmt.close();
+ }
+ return record;
+ }
+
+ private TransactionRecord prepareTransactionRecord(TransactionCache cache, int transactionNumber, int branchId, String comment, Date timestamp, int authorArtId, int commitArtId, TransactionDetailsType txType) throws OseeCoreException {
+ TransactionRecordFactory factory = factoryProvider.getOseeFactoryService().getTransactionFactory();
+ TransactionRecord record =
+ factory.createOrUpdate(cache, transactionNumber, branchId, comment, timestamp, authorArtId, commitArtId,
+ txType);
+ record.setBranchCache(branchCache);
+ record.clearDirty();
+ return record;
+ }
+
+ @Override
+ public void load(TransactionCache transactionCache) throws OseeCoreException {
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/IBranchUpdateEvent.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/IBranchUpdateEvent.java new file mode 100644 index 00000000000..b0323434e64 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/cache/IBranchUpdateEvent.java @@ -0,0 +1,23 @@ +/*******************************************************************************
+ * Copyright (c) 2009 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.cache;
+
+import java.util.Collection;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.model.Branch;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public interface IBranchUpdateEvent {
+
+ void send(Collection<Branch> branches) throws OseeCoreException;
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/Activator.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/Activator.java new file mode 100644 index 00000000000..c72b45c0157 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/Activator.java @@ -0,0 +1,46 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.internal;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.eclipse.osee.framework.core.util.AbstractTrackingHandler;
+import org.eclipse.osee.framework.core.util.ServiceDependencyTracker;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ public static final String PLUGIN_ID = "org.eclipse.osee.framework.core.datastore";
+
+ private final List<ServiceDependencyTracker> services;
+
+ public Activator() {
+ this.services = new ArrayList<ServiceDependencyTracker>();
+ }
+
+ public void start(BundleContext context) throws Exception {
+ createService(context, new OseeCachingServiceRegistrationHandler());
+ }
+
+ public void stop(BundleContext context) throws Exception {
+ for (ServiceDependencyTracker service : services) {
+ service.close();
+ }
+ services.clear();
+ }
+
+ private void createService(BundleContext context, AbstractTrackingHandler handler) {
+ ServiceDependencyTracker service = new ServiceDependencyTracker(context, handler);
+ services.add(service);
+ service.open();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/CoreOseeSchemaResource.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/CoreOseeSchemaResource.java new file mode 100644 index 00000000000..870919153bb --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/CoreOseeSchemaResource.java @@ -0,0 +1,30 @@ +/*
+ * Created on Jun 23, 2010
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.core.datastore.internal;
+
+import java.io.InputStream;
+import java.net.URL;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.osee.framework.core.datastore.IOseeSchemaResource;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeExceptions;
+import org.osgi.framework.Bundle;
+
+public class CoreOseeSchemaResource implements IOseeSchemaResource {
+
+ @Override
+ public InputStream getContent() throws OseeCoreException {
+ InputStream inputStream = null;
+ try {
+ Bundle bundle = Platform.getBundle("org.eclipse.osee.framework.core.datastore");
+ URL url = bundle.getEntry("support/SKYNET.VERSIONING.SCHEMA.xml");
+ inputStream = url.openStream();
+ } catch (Exception ex) {
+ OseeExceptions.wrapAndThrow(ex);
+ }
+ return inputStream;
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/OseeCachingServiceRegistrationHandler.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/OseeCachingServiceRegistrationHandler.java new file mode 100644 index 00000000000..25ec87f4134 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/OseeCachingServiceRegistrationHandler.java @@ -0,0 +1,105 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.internal;
+
+import java.util.Map;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.core.server.IApplicationServerLookup;
+import org.eclipse.osee.framework.core.server.IApplicationServerLookupProvider;
+import org.eclipse.osee.framework.core.server.IApplicationServerManager;
+import org.eclipse.osee.framework.core.services.IOseeCachingService;
+import org.eclipse.osee.framework.core.services.IOseeCachingServiceFactory;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryService;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.core.translation.IDataTranslationService;
+import org.eclipse.osee.framework.core.translation.IDataTranslationServiceProvider;
+import org.eclipse.osee.framework.core.util.AbstractTrackingHandler;
+import org.eclipse.osee.framework.database.IOseeDatabaseService;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class OseeCachingServiceRegistrationHandler extends AbstractTrackingHandler {
+
+ private final static Class<?>[] SERVICE_DEPENDENCIES =
+ new Class<?>[] {IOseeDatabaseService.class, IOseeModelFactoryService.class, IDataTranslationService.class,
+ IApplicationServerLookup.class, IApplicationServerManager.class};
+
+ private ServiceRegistration factoryRegistration;
+ private ServiceRegistration cachingServiceRegistration;
+
+ @Override
+ public Class<?>[] getDependencies() {
+ return SERVICE_DEPENDENCIES;
+ }
+
+ @Override
+ public void onActivate(BundleContext context, Map<Class<?>, Object> services) {
+ IOseeCachingServiceFactory factory = createCachingFactoryService(services);
+ IOseeCachingService cachingService = factory.createCachingService();
+
+ factoryRegistration = context.registerService(IOseeCachingServiceFactory.class.getName(), factory, null);
+ cachingServiceRegistration = context.registerService(IOseeCachingService.class.getName(), cachingService, null);
+ }
+
+ @Override
+ public void onDeActivate() {
+ if (factoryRegistration != null) {
+ factoryRegistration.unregister();
+ }
+ if (cachingServiceRegistration != null) {
+ cachingServiceRegistration.unregister();
+ }
+ }
+
+ private IOseeCachingServiceFactory createCachingFactoryService(Map<Class<?>, Object> services) {
+ final IOseeDatabaseService dbService = getService(IOseeDatabaseService.class, services);
+ final IOseeModelFactoryService modelService = getService(IOseeModelFactoryService.class, services);
+ final IDataTranslationService translationService = getService(IDataTranslationService.class, services);
+ final IApplicationServerLookup lookupService = getService(IApplicationServerLookup.class, services);
+ final IApplicationServerManager appManager = getService(IApplicationServerManager.class, services);
+ IOseeDatabaseServiceProvider dbProvider = new IOseeDatabaseServiceProvider() {
+ @Override
+ public IOseeDatabaseService getOseeDatabaseService() throws OseeDataStoreException {
+ return dbService;
+ }
+ };
+
+ IOseeModelFactoryServiceProvider modelProvider = new IOseeModelFactoryServiceProvider() {
+
+ @Override
+ public IOseeModelFactoryService getOseeFactoryService() throws OseeCoreException {
+ return modelService;
+ }
+ };
+
+ IDataTranslationServiceProvider txProvider = new IDataTranslationServiceProvider() {
+
+ @Override
+ public IDataTranslationService getTranslationService() throws OseeCoreException {
+ return translationService;
+ }
+ };
+
+ IApplicationServerLookupProvider lookupProvider = new IApplicationServerLookupProvider() {
+
+ @Override
+ public IApplicationServerLookup getApplicationServerLookupService() throws OseeCoreException {
+ return lookupService;
+ }
+ };
+ return new ServerOseeCachingServiceFactory(dbProvider, modelProvider, txProvider, lookupProvider, appManager);
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/ServerOseeCachingServiceFactory.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/ServerOseeCachingServiceFactory.java new file mode 100644 index 00000000000..a181b0b45c0 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/internal/ServerOseeCachingServiceFactory.java @@ -0,0 +1,82 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.internal;
+
+import org.eclipse.osee.framework.core.datastore.cache.BranchUpdateEventImpl;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseArtifactTypeAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseAttributeTypeAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseBranchAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseOseeEnumTypeAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseRelationTypeAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.DatabaseTransactionRecordAccessor;
+import org.eclipse.osee.framework.core.datastore.cache.IBranchUpdateEvent;
+import org.eclipse.osee.framework.core.model.OseeCachingService;
+import org.eclipse.osee.framework.core.model.cache.ArtifactTypeCache;
+import org.eclipse.osee.framework.core.model.cache.AttributeTypeCache;
+import org.eclipse.osee.framework.core.model.cache.BranchCache;
+import org.eclipse.osee.framework.core.model.cache.IOseeDataAccessor;
+import org.eclipse.osee.framework.core.model.cache.OseeEnumTypeCache;
+import org.eclipse.osee.framework.core.model.cache.RelationTypeCache;
+import org.eclipse.osee.framework.core.model.cache.TransactionCache;
+import org.eclipse.osee.framework.core.model.type.AttributeType;
+import org.eclipse.osee.framework.core.server.IApplicationServerLookupProvider;
+import org.eclipse.osee.framework.core.server.IApplicationServerManager;
+import org.eclipse.osee.framework.core.services.IOseeCachingService;
+import org.eclipse.osee.framework.core.services.IOseeCachingServiceFactory;
+import org.eclipse.osee.framework.core.services.IOseeModelFactoryServiceProvider;
+import org.eclipse.osee.framework.core.translation.IDataTranslationServiceProvider;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class ServerOseeCachingServiceFactory implements IOseeCachingServiceFactory {
+
+ private final IOseeDatabaseServiceProvider databaseProvider;
+ private final IOseeModelFactoryServiceProvider factoryProvider;
+ private final IDataTranslationServiceProvider txProvider;
+ private final IApplicationServerLookupProvider serverLookUpProvider;
+ private final IApplicationServerManager appManager;
+
+ public ServerOseeCachingServiceFactory(IOseeDatabaseServiceProvider databaseProvider, IOseeModelFactoryServiceProvider factoryProvider, IDataTranslationServiceProvider txProvider, IApplicationServerLookupProvider serverLookUpProvider, IApplicationServerManager appManager) {
+ this.databaseProvider = databaseProvider;
+ this.factoryProvider = factoryProvider;
+ this.txProvider = txProvider;
+ this.serverLookUpProvider = serverLookUpProvider;
+ this.appManager = appManager;
+ }
+
+ public IOseeCachingService createCachingService() {
+ OseeEnumTypeCache oseeEnumTypeCache =
+ new OseeEnumTypeCache(new DatabaseOseeEnumTypeAccessor(databaseProvider, factoryProvider));
+
+ IOseeDataAccessor<AttributeType> attrAccessor =
+ new DatabaseAttributeTypeAccessor(databaseProvider, factoryProvider, oseeEnumTypeCache);
+
+ AttributeTypeCache attributeCache = new AttributeTypeCache(attrAccessor);
+
+ TransactionCache txCache = new TransactionCache();
+ IBranchUpdateEvent branchEventSender = new BranchUpdateEventImpl(txProvider, appManager, serverLookUpProvider);
+ BranchCache branchCache =
+ new BranchCache(new DatabaseBranchAccessor(databaseProvider, factoryProvider, branchEventSender, txCache));
+ txCache.setAccessor(new DatabaseTransactionRecordAccessor(databaseProvider, factoryProvider, branchCache));
+
+ ArtifactTypeCache artifactCache =
+ new ArtifactTypeCache(new DatabaseArtifactTypeAccessor(databaseProvider, factoryProvider, branchCache,
+ attributeCache));
+
+ RelationTypeCache relationCache =
+ new RelationTypeCache(new DatabaseRelationTypeAccessor(databaseProvider, factoryProvider, artifactCache));
+
+ return new OseeCachingService(branchCache, txCache, artifactCache, attributeCache, relationCache,
+ oseeEnumTypeCache);
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/AppliesToClause.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/AppliesToClause.java new file mode 100644 index 00000000000..48f7627d7e6 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/AppliesToClause.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.core.datastore.schema.data; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class AppliesToClause implements Xmlizable { + public static final String APPLIES_TO_TAG = "AppliesTo"; + + public enum OrderType { + Undefined, Ascending, Descending; + } + + public enum AppliesToEntries { + id, sort; + } + + private String columnName; + private OrderType orderType; + + public AppliesToClause(String columnName, OrderType orderType) { + this.columnName = columnName; + this.orderType = orderType; + } + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public OrderType getOrderType() { + return orderType; + } + + public void setOrderType(OrderType orderType) { + this.orderType = orderType; + } + + public String toString() { + return String.format("%s:[%s]\t%s:[%s]", AppliesToEntries.id.name(), columnName, AppliesToEntries.sort.name(), + orderType); + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof AppliesToClause == false) { + return false; + } + if (this == otherObject) { + return true; + } + AppliesToClause that = (AppliesToClause) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.columnName, that.getColumnName()).append( + this.orderType, that.getOrderType()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(23, 37).append(columnName).append(orderType).toHashCode(); + } + + public Element toXml(Document doc) { + Element element = doc.createElement(APPLIES_TO_TAG); + element.setAttribute(AppliesToEntries.id.name(), columnName); + if (!orderType.equals(OrderType.Undefined)) { + element.setAttribute(AppliesToEntries.sort.name(), orderType.name()); + } + return element; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnDbData.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnDbData.java new file mode 100644 index 00000000000..d261388feac --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnDbData.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +/** + * @author Roberto E. Escobar + */ +public class ColumnDbData { + private String columnName; + private String columnValue; + + public ColumnDbData(String columnName, String columnValue) { + this.columnName = columnName; + this.columnValue = columnValue; + } + + public String getColumnName() { + return columnName; + } + + public String getColumnValue() { + return columnValue; + } + + public String toString() { + return "[" + columnName + ", " + columnValue + "]"; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnMetadata.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnMetadata.java new file mode 100644 index 00000000000..9101539dc85 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ColumnMetadata.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableSections; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ColumnMetadata implements Xmlizable { + private final Map<ColumnFields, String> columnFields; + + public ColumnMetadata(String columnId) { + columnFields = new HashMap<ColumnFields, String>(); + columnFields.put(ColumnFields.id, columnId); + } + + public String getId() { + return getColumnField(ColumnFields.id); + } + + public Map<ColumnFields, String> getColumnFields() { + return columnFields; + } + + public void addColumnField(ColumnFields field, String value) { + columnFields.put(field, value); + } + + public String getColumnField(ColumnFields field) { + if (columnFields.containsKey(field)) { + return columnFields.get(field); + } + return ""; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof ColumnMetadata == false) { + return false; + } + if (this == otherObject) { + return true; + } + ColumnMetadata that = (ColumnMetadata) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.columnFields, + that.getColumnFields()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(101, 83).append(columnFields).toHashCode(); + } + + @Override + public String toString() { + String toReturn = TableSections.Column + ": "; + Set<ColumnFields> keys = columnFields.keySet(); + for (ColumnFields field : keys) { + String value = columnFields.get(field); + toReturn += "\t" + field + "[" + value + "]"; + } + return toReturn; + } + + public Element toXml(Document doc) { + Element columnElement = doc.createElement(TableSections.Column.toString()); + for (ColumnFields key : columnFields.keySet()) { + columnElement.setAttribute(key.toString(), columnFields.get(key)); + } + return columnElement; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintElement.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintElement.java new file mode 100644 index 00000000000..8d7d0fa4368 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintElement.java @@ -0,0 +1,141 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.osee.framework.core.datastore.schema.data;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableSections;
+import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class ConstraintElement implements Xmlizable {
+
+ public enum ConstraintFields {
+ id, schema, type, appliesTo, deferrable
+ };
+
+ private final ConstraintTypes constraintType;
+ private final boolean deferrable;
+ private String schema;
+ private String id;
+ private final List<String> columns;
+
+ public ConstraintElement(ConstraintTypes constraintType, String schema, String id, boolean deferrable) {
+ this.schema = schema.toUpperCase();
+ this.schema = this.schema.trim();
+ this.id = id.toUpperCase();
+ this.id = this.id.trim();
+ this.deferrable = deferrable;
+ this.constraintType = constraintType;
+ this.columns = new ArrayList<String>();
+ }
+
+ public List<String> getColumns() {
+ return columns;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ public void addColumn(String columnName) {
+ columnName = columnName.toUpperCase();
+ columnName = columnName.trim();
+ this.columns.add(columnName);
+ }
+
+ public void setId(String id) {
+ id = id.toUpperCase();
+ id = id.trim();
+ this.id = id;
+ }
+
+ public void setSchema(String schema) {
+ schema = schema.toUpperCase();
+ schema = schema.trim();
+ this.schema = schema;
+ }
+
+ public String getFullyQualifiedId() {
+ if (schema != null && !schema.equals("")) {
+ return schema + "." + id;
+ } else {
+ return id;
+ }
+ }
+
+ /**
+ * @return Returns the deferrable.
+ */
+ public boolean isDeferrable() {
+ return deferrable;
+ }
+
+ public ConstraintTypes getConstraintType() {
+ return constraintType;
+ }
+
+ public String getCommaSeparatedColumnsList() {
+ return org.eclipse.osee.framework.jdk.core.util.Collections.toString(columns, ",");
+ }
+
+ @Override
+ public String toString() {
+ String toReturn = TableSections.Constraint + ": ";
+ toReturn += "\t" + ConstraintFields.schema + "[" + schema + "]";
+ toReturn += "\t" + ConstraintFields.id + "[" + id + "]";
+ toReturn += "\t" + ConstraintFields.type + "[" + constraintType.toString() + "]";
+ toReturn += "\t" + ConstraintFields.appliesTo + "[" + getCommaSeparatedColumnsList() + "]";
+ toReturn += "\t" + ConstraintFields.deferrable + "[" + Boolean.toString(deferrable) + "]";
+ return toReturn;
+ }
+
+ public Element toXml(Document doc) {
+ Element constraintElement = doc.createElement(TableSections.Constraint.toString());
+ constraintElement.setAttribute(ConstraintFields.schema.name(), schema);
+ constraintElement.setAttribute(ConstraintFields.id.name(), id);
+ constraintElement.setAttribute(ConstraintFields.type.name(), constraintType.toString());
+ constraintElement.setAttribute(ConstraintFields.appliesTo.name(), getCommaSeparatedColumnsList());
+ constraintElement.setAttribute(ConstraintFields.deferrable.name(), Boolean.toString(deferrable));
+ return constraintElement;
+ }
+
+ @Override
+ public boolean equals(Object otherObject) {
+ if (otherObject instanceof ConstraintElement == false) {
+ return false;
+ }
+ if (this == otherObject) {
+ return true;
+ }
+ ConstraintElement that = (ConstraintElement) otherObject;
+ return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.constraintType,
+ that.getConstraintType()).append(this.schema, that.getSchema()).append(this.id, that.getId()).append(
+ this.columns, that.getColumns()).append(this.deferrable, that.deferrable).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(37, 11).append(constraintType).append(schema).append(id).append(columns).append(
+ deferrable).toHashCode();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintFactory.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintFactory.java new file mode 100644 index 00000000000..01b84e54efd --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintFactory.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +/** + * @author Roberto E. Escobar + */ +public class ConstraintFactory { + + public static ConstraintElement getConstraint(ConstraintTypes constraintType, String schema, String id, boolean deferrable) { + ConstraintElement element = null; + if (constraintType != null) { + switch (constraintType) { + case FOREIGN_KEY: + element = new ForeignKey(constraintType, schema, id, deferrable); + break; + case PRIMARY_KEY: + case UNIQUE: + case CHECK: + default: + element = new ConstraintElement(constraintType, schema, id, deferrable); + break; + } + } + return element; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintTypes.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintTypes.java new file mode 100644 index 00000000000..3497e44a7e5 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ConstraintTypes.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +/** + * @author Roberto E. Escobar + */ +public enum ConstraintTypes { + PRIMARY_KEY, FOREIGN_KEY, UNIQUE, CHECK; + + public String toString() { + String toReturn = super.toString(); + toReturn = toReturn.replaceAll("_", " "); + return toReturn; + } + + public static ConstraintTypes textToType(String text) { + ConstraintTypes[] typesArray = ConstraintTypes.values(); + for (ConstraintTypes type : typesArray) { + if (type.toString().equals(text.toUpperCase())) { + return type; + } + } + return null; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ForeignKey.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ForeignKey.java new file mode 100644 index 00000000000..d41d3bf2693 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ForeignKey.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ForeignKey extends ConstraintElement implements Xmlizable { + + List<ReferenceClause> references; + + public ForeignKey(ConstraintTypes constraintType, String schema, String id, boolean deferrable) { + super(constraintType, schema, id, deferrable); + references = new ArrayList<ReferenceClause>(); + } + + public void addReference(ReferenceClause reference) { + references.add(reference); + } + + public List<ReferenceClause> getReferences() { + return references; + } + + public Set<String> getReferencedTables() { + Set<String> refTables = new TreeSet<String>(); + for (ReferenceClause ref : references) { + refTables.add(ref.getFullyQualifiedTableName()); + } + return refTables; + } + + @Override + public String toString() { + String toReturn = super.toString(); + for (ReferenceClause reference : references) { + toReturn += "\n\t\t" + reference.toString(); + } + return toReturn; + } + + @Override + public Element toXml(Document doc) { + Element parent = super.toXml(doc); + for (ReferenceClause reference : references) { + parent.appendChild(reference.toXml(doc)); + } + return parent; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/IndexElement.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/IndexElement.java new file mode 100644 index 00000000000..990c4228590 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/IndexElement.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class IndexElement implements Xmlizable { + + public enum IndexFields { + id, mySqlIgnore, type, tablespace; + } + + private String id; + private String indexType; + private List<AppliesToClause> appliesToList; + private boolean ignoreMySql = false; + private String tablespace; + + public IndexElement(String id) { + this.id = id; + this.appliesToList = new ArrayList<AppliesToClause>(); + this.indexType = ""; + this.tablespace = ""; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void addAppliesTo(String name, OrderType type) { + appliesToList.add(new AppliesToClause(name, type)); + } + + public List<AppliesToClause> getAppliesToList() { + return appliesToList; + } + + public String toString() { + StringBuilder toReturn = new StringBuilder(); + toReturn.append(" Index: " + id); + toReturn.append(getAppliesToAsString()); + return toReturn.toString(); + } + + public Element toXml(Document doc) { + Element element = doc.createElement(TableElement.TableSections.Index.name()); + element.setAttribute(IndexFields.id.name(), id); + for (AppliesToClause clause : appliesToList) { + element.appendChild(clause.toXml(doc)); + } + return element; + } + + public String getAppliesToAsString() { + StringBuilder toReturn = new StringBuilder(); + for (int index = 0; index < appliesToList.size(); index++) { + toReturn.append("\n\t\tApplies to " + appliesToList.get(index)); + } + return toReturn.toString(); + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof IndexElement == false) { + return false; + } + if (this == otherObject) { + return true; + } + IndexElement that = (IndexElement) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.appliesToList, + that.getAppliesToList()).append(this.id, that.getId()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(113, 67).append(id).append(appliesToList).toHashCode(); + } + + public void setMySqlIgnore(boolean b) { + this.ignoreMySql = b; + } + + public void setIndexType(String indexType) { + if (indexType != null) { + this.indexType = indexType; + } + } + + public String getIndexType() { + return indexType; + } + + public boolean ignoreMySql() { + return this.ignoreMySql; + } + + public String getTablespace() { + return Strings.isValid(tablespace) ? tablespace : ""; + } + + public void setTablespace(String tablespace) { + this.tablespace = tablespace; + } +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ReferenceClause.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ReferenceClause.java new file mode 100644 index 00000000000..17cbc88c5e3 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/ReferenceClause.java @@ -0,0 +1,154 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.osee.framework.core.datastore.schema.data;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class ReferenceClause implements Xmlizable {
+ public static final String REFERENCES_TAG = "References";
+
+ public enum ReferencesFields {
+ schema, table, column, onUpdate, onDelete;
+ }
+
+ public enum OnDeleteEnum {
+ NO_ACTION, RESTRICT, CASCADE, SET_NULL, UNSPECIFIED;
+
+ @Override
+ public String toString() {
+ String toReturn = super.toString();
+ toReturn = toReturn.replaceAll("_", " ");
+ return toReturn;
+ }
+ }
+
+ public enum OnUpdateEnum {
+ NO_ACTION, RESTRICT, UNSPECIFIED;
+
+ @Override
+ public String toString() {
+ String toReturn = super.toString();
+ toReturn = toReturn.replaceAll("_", " ");
+ return toReturn;
+ }
+ }
+
+ private String schema;
+ private String table;
+ List<String> columns;
+ OnDeleteEnum onDeleteAction;
+ OnUpdateEnum onUpdateAction;
+
+ public ReferenceClause(String schema, String table) {
+ this.schema = schema.toUpperCase();
+ this.schema = this.schema.trim();
+ this.table = table.toUpperCase();
+ this.table = this.table.trim();
+ this.columns = new ArrayList<String>();
+ this.onDeleteAction = OnDeleteEnum.UNSPECIFIED;
+ this.onUpdateAction = OnUpdateEnum.UNSPECIFIED;
+ }
+
+ public void setSchema(String schema) {
+ this.schema = schema;
+ }
+
+ public OnDeleteEnum getOnDeleteAction() {
+ return onDeleteAction;
+ }
+
+ public OnUpdateEnum getOnUpdateAction() {
+ return onUpdateAction;
+ }
+
+ public void setOnDeleteAction(OnDeleteEnum onDeleteAction) {
+ this.onDeleteAction = onDeleteAction;
+ }
+
+ public void setOnUpdateAction(OnUpdateEnum onUpdateAction) {
+ this.onUpdateAction = onUpdateAction;
+ }
+
+ public void addColumn(String column) {
+ column = column.toUpperCase();
+ column = column.trim();
+ columns.add(column);
+ }
+
+ public String getFullyQualifiedTableName() {
+ return schema + "." + table;
+ }
+
+ public List<String> getColumns() {
+ return columns;
+ }
+
+ public String getCommaSeparatedColumnsList() {
+ return org.eclipse.osee.framework.jdk.core.util.Collections.toString(columns, ",");
+ }
+
+ @Override
+ public String toString() {
+ String toReturn = REFERENCES_TAG + ": " + getFullyQualifiedTableName();
+ toReturn += "\t[";
+ for (String column : columns) {
+ toReturn += column + " ";
+ }
+ toReturn += "]";
+ return toReturn;
+ }
+
+ public Element toXml(Document doc) {
+ Element refElement = doc.createElement(REFERENCES_TAG);
+ refElement.setAttribute(ReferencesFields.schema.name(), schema);
+ refElement.setAttribute(ReferencesFields.table.name(), table);
+ refElement.setAttribute(ReferencesFields.column.name(), getCommaSeparatedColumnsList());
+
+ if (!onDeleteAction.equals(OnDeleteEnum.UNSPECIFIED)) {
+ refElement.setAttribute(ReferencesFields.onDelete.name(), onDeleteAction.toString());
+ }
+
+ if (!onUpdateAction.equals(OnUpdateEnum.UNSPECIFIED)) {
+ refElement.setAttribute(ReferencesFields.onUpdate.name(), onUpdateAction.toString());
+ }
+ return refElement;
+ }
+
+ @Override
+ public boolean equals(Object otherObject) {
+ if (otherObject instanceof ReferenceClause == false) {
+ return false;
+ }
+ if (this == otherObject) {
+ return true;
+ }
+ ReferenceClause that = (ReferenceClause) otherObject;
+ return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.getFullyQualifiedTableName(),
+ that.getFullyQualifiedTableName()).append(this.columns, that.getColumns()).append(this.onDeleteAction,
+ that.getOnDeleteAction()).append(this.onUpdateAction, that.getOnUpdateAction()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(113, 67).append(schema).append(table).append(columns).append(onDeleteAction).append(
+ onUpdateAction).toHashCode();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaData.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaData.java new file mode 100644 index 00000000000..e66d4586950 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaData.java @@ -0,0 +1,277 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class SchemaData implements Xmlizable { + + public static final String ROOT_TAG = "TableConfig"; + private List<TableElement> tableDefinitions; + private final SchemaDataLookup schemaLookup; + + private final boolean isSorted; + + public SchemaData() { + this.tableDefinitions = new ArrayList<TableElement>(); + this.isSorted = false; + this.schemaLookup = new SchemaDataLookup(this); + } + + public void setTableDataSpaceName(String tableDataSpace) { + for (TableElement table : getTableMap().values()) { + table.setTablespace(tableDataSpace); + } + } + + public void setIndexDataSpaceName(String indexDataSpace) { + for (TableElement table : getTableMap().values()) { + for (IndexElement indexElement : table.getIndexData()) { + indexElement.setTablespace(indexDataSpace); + } + } + } + + public List<TableElement> getTablesOrderedByDependency() { + sortTablesForConstraints(); + markIdentityColumns(); + return tableDefinitions; + } + + public Set<String> getTablesToBackup() { + Set<String> backupTables = new TreeSet<String>(); + for (TableElement table : tableDefinitions) { + if (table.isBackupDataSet()) { + backupTables.add(table.getFullyQualifiedTableName()); + } + } + return backupTables; + } + + public Map<String, Set<String>> getTablesToImport(String defaultSource) { + Map<String, Set<String>> importTables = new HashMap<String, Set<String>>(); + for (TableElement table : tableDefinitions) { + if (table.isImportDataSet()) { + String importFrom = table.getImportFrom(); + if (!Strings.isValid(importFrom)) { + importFrom = defaultSource; + } + Set<String> tableSet; + if (importTables.containsKey(importFrom)) { + tableSet = importTables.get(importFrom); + } else { + tableSet = new TreeSet<String>(); + } + tableSet.add(table.getFullyQualifiedTableName()); + importTables.put(importFrom, tableSet); + } + } + return importTables; + } + + public void addTableDefinition(TableElement table) { + tableDefinitions.add(table); + } + + @Override + public String toString() { + String toReturn = ""; + for (TableElement table : tableDefinitions) { + toReturn += table.toString(); + } + return toReturn; + } + + public Document getXmlDocument() throws ParserConfigurationException { + Document doc = Jaxp.newDocument(); + Element root = doc.createElement(ROOT_TAG); + doc.appendChild(root); + for (TableElement table : tableDefinitions) { + root.appendChild(table.toXml(doc)); + } + return doc; + } + + public Element toXml(Document doc) { + return null; + } + + private void sortTablesForConstraints() { + this.tableDefinitions = sortTablesForConstraints(this.tableDefinitions); + } + + private boolean canCreate(TableElement table, Set<String> canCreate) { + Set<String> dependencies = table.getTableDependency(); + if (canCreate.containsAll(dependencies)) { + return true; + } + return false; + } + + private void markIdentityColumns() { + for (TableElement aTable : tableDefinitions) { + determineIdentityColumns(aTable); + } + } + + private void determineIdentityColumns(TableElement tableDef) { + List<String> primaryKeys = new ArrayList<String>(); + + // first get all of the vars used for the primary key + List<ConstraintElement> constraints = tableDef.getConstraints(); + for (ConstraintElement constraint : constraints) { + if (constraint.getConstraintType().equals(ConstraintTypes.PRIMARY_KEY)) { + List<String> columns = constraint.getColumns(); + for (String column : columns) { + primaryKeys.add(column); + } + } + } + + // now go through and remove any of the primary key vars that are foreign keys + List<ForeignKey> foreignKeys = tableDef.getForeignKeyConstraints(); + for (ForeignKey fkConstraint : foreignKeys) { + List<String> columns = fkConstraint.getColumns(); + for (String column : columns) { + primaryKeys.remove(column); + } + } + + // now we should only be left with those primary keys that are identities. + // we set them by setting their corresponding identity column to true, a little hokey but that + // way we don't have to create special data structures for the column + Map<String, ColumnMetadata> columns = tableDef.getColumns(); + Set<String> columnKeys = columns.keySet(); + for (String key : columnKeys) { + ColumnMetadata column = columns.get(key); + if (primaryKeys.contains(column.getId())) { + column.addColumnField(ColumnFields.identity, Boolean.TRUE.toString()); + } + } + } + + private List<TableElement> sortTablesForConstraints(List<TableElement> tables) { + List<TableElement> sorted = new ArrayList<TableElement>(); + Set<String> canCreate = new HashSet<String>(); + + Map<TableElement, Boolean> toSort = new HashMap<TableElement, Boolean>(); + + for (TableElement aTable : tables) { + if (aTable.hasForeignKey()) { + toSort.put(aTable, false); + } else { + sorted.add(aTable); + canCreate.add(aTable.getFullyQualifiedTableName()); + } + } + + // Prevent for endless loops caused by + // foreign/primary key discrepancies + int guard = toSort.size() * 2; + int count = 0; + while (toSort.containsValue(false) && count < guard) { + Set<TableElement> elements = toSort.keySet(); + + for (TableElement aTable : elements) { + + if (!toSort.get(aTable)) { + if (canCreate(aTable, canCreate)) { + canCreate.add(aTable.getFullyQualifiedTableName()); + sorted.add(aTable); + toSort.put(aTable, true); + } + } + } + count++; + } + + // If we were stuck in an endless loop copy all unsortable tables + // to the end of the sorted array and return + if (toSort.containsValue(false)) { + Set<TableElement> elements = toSort.keySet(); + for (TableElement aTable : elements) { + if (!toSort.get(aTable)) { + canCreate.add(aTable.getFullyQualifiedTableName()); + sorted.add(aTable); + toSort.put(aTable, true); + } + } + } + + return sorted; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof SchemaData == false) { + return false; + } + if (this == otherObject) { + return true; + } + SchemaData that = (SchemaData) otherObject; + return hasEqualState(that); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(37, 11).append(tableDefinitions).append(isSorted).append(schemaLookup).toHashCode(); + } + + public Map<String, TableElement> getTableMap() { + Map<String, TableElement> tableMap = new HashMap<String, TableElement>(); + for (TableElement table : tableDefinitions) { + tableMap.put(table.getFullyQualifiedTableName(), table); + } + return tableMap; + } + + public boolean hasEqualState(SchemaData that) { + EqualsBuilder equalsBuilder = new EqualsBuilder(); + equalsBuilder.appendSuper(super.equals(that)); + + Map<String, TableElement> thisTableMap = this.getTableMap(); + Map<String, TableElement> thatTableMap = that.getTableMap(); + + Set<String> thisKey1 = thisTableMap.keySet(); + Set<String> thatKey2 = thatTableMap.keySet(); + + boolean toReturn = true; + if (thisKey1.equals(thatKey2)) { + for (String key : thisKey1) { + equalsBuilder.append(thisTableMap.get(key), thatTableMap.get(key)); + } + toReturn &= equalsBuilder.isEquals(); + } else { + toReturn = false; + } + return toReturn; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaDataLookup.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaDataLookup.java new file mode 100644 index 00000000000..b300e9d31cc --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaDataLookup.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.List; +import java.util.Map; + +/** + * @author Roberto E. Escobar + */ +public class SchemaDataLookup { + + private SchemaData schemaData; + + public SchemaDataLookup(SchemaData schemaData) { + this.schemaData = schemaData; + } + + public ColumnMetadata getColumnDefinition(TableElement table, String columnId) { + Map<String, ColumnMetadata> columns = table.getColumns(); + return getColumnDefinition(columns, columnId); + } + + public static ColumnMetadata getColumnDefinition(Map<String, ColumnMetadata> columns, String columnId) { + if (columns.containsKey(columnId)) { + return columns.get(columnId); + } + return null; + } + + public TableElement getTableDefinition(String tableName) { + List<TableElement> list = schemaData.getTablesOrderedByDependency(); + for (TableElement table : list) { + return table; + } + return null; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaXmlParser.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaXmlParser.java new file mode 100644 index 00000000000..d989adb8c5b --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/SchemaXmlParser.java @@ -0,0 +1,220 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.io.BufferedInputStream; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import org.eclipse.osee.framework.core.datastore.IOseeSchemaProvider; +import org.eclipse.osee.framework.core.datastore.IOseeSchemaResource; +import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause.AppliesToEntries; +import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement.ConstraintFields; +import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement.IndexFields; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.ReferencesFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableSections; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableTags; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + +/** + * @author Roberto E. Escobar + */ +public class SchemaXmlParser { + + public SchemaXmlParser() { + } + + private void parseTableDescription(Element element, TableElement tableEntry) { + NamedNodeMap attributes = element.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + Attr attribute = (Attr) attributes.item(i); + TableDescriptionFields tableField = TableDescriptionFields.valueOf(attribute.getName()); + tableEntry.addTableDescription(tableField, attribute.getValue()); + } + } + + private void parseColumnEntries(Element element, TableElement tableEntry) { + List<Element> columns = Jaxp.getChildDirects(element, TableSections.Column.name()); + for (Element column : columns) { + NamedNodeMap attributes = column.getAttributes(); + ColumnMetadata columnMetadata = new ColumnMetadata(""); + for (int i = 0; i < attributes.getLength(); i++) { + Attr attribute = (Attr) attributes.item(i); + ColumnFields columnField = ColumnFields.valueOf(attribute.getName()); + columnMetadata.addColumnField(columnField, attribute.getValue().toUpperCase()); + } + tableEntry.addColumn(columnMetadata); + } + } + + private void parseConstraintEntries(Element element, TableElement tableEntry) { + List<Element> constraints = Jaxp.getChildDirects(element, TableSections.Constraint.name()); + for (Element constraint : constraints) { + Attr type = constraint.getAttributeNode(ConstraintFields.type.name()); + Attr id = constraint.getAttributeNode(ConstraintFields.id.name()); + String schema = constraint.getAttribute(ConstraintFields.schema.name()); + String deferrable = constraint.getAttribute(ConstraintFields.deferrable.name()); + if (type != null && id != null) { + + ConstraintElement constraintElement = + ConstraintFactory.getConstraint(ConstraintTypes.textToType(type.getValue().toUpperCase()), + schema.toUpperCase(), id.getValue().toUpperCase(), + deferrable.equalsIgnoreCase(Boolean.toString(true))); + + Attr appliesTo = constraint.getAttributeNode(ConstraintFields.appliesTo.name()); + if (appliesTo != null) { + String[] columns = appliesTo.getValue().split(","); + for (String column : columns) { + constraintElement.addColumn(column.toUpperCase()); + } + } + + if (constraintElement instanceof ForeignKey) { + Element reference = Jaxp.getChildDirect(constraint, ReferenceClause.REFERENCES_TAG); + if (reference != null) { + Attr table = reference.getAttributeNode(ReferencesFields.table.name()); + Attr refColumn = reference.getAttributeNode(ReferencesFields.column.name()); + Attr onUpdate = reference.getAttributeNode(ReferencesFields.onUpdate.name()); + Attr onDelete = reference.getAttributeNode(ReferencesFields.onDelete.name()); + String refSchema = reference.getAttribute(ReferencesFields.schema.name()); + + if (table != null) { + + ReferenceClause references = + new ReferenceClause(refSchema.toUpperCase(), table.getValue().toUpperCase()); + if (refColumn != null) { + String[] columns = refColumn.getValue().split(","); + for (String column : columns) { + references.addColumn(column.toUpperCase()); + } + } + if (onUpdate != null) { + OnUpdateEnum[] values = OnUpdateEnum.values(); + for (OnUpdateEnum value : values) { + if (value.toString().equals(onUpdate.getValue().toUpperCase())) { + references.setOnUpdateAction(value); + } + } + } + if (onDelete != null) { + OnDeleteEnum[] values = OnDeleteEnum.values(); + for (OnDeleteEnum value : values) { + if (value.toString().equals(onDelete.getValue().toUpperCase())) { + references.setOnDeleteAction(value); + } + } + } + ((ForeignKey) constraintElement).addReference(references); + } + } + } + tableEntry.addConstraint(constraintElement); + } + } + } + + private void parseIndexDataEntries(Element element, TableElement tableEntry) { + List<Element> indexDataList = Jaxp.getChildDirects(element, TableSections.Index.name()); + for (Element indexDataEntry : indexDataList) { + String id = indexDataEntry.getAttribute(IndexFields.id.name()); + String ignore = indexDataEntry.getAttribute(IndexFields.mySqlIgnore.name()); + Attr indexType = indexDataEntry.getAttributeNode(IndexFields.type.name()); + String tablespace = indexDataEntry.getAttribute(IndexFields.tablespace.name()); + if (id.length() > 0) { + IndexElement indexData = new IndexElement(id); + if (Boolean.parseBoolean(ignore)) { + indexData.setMySqlIgnore(true); + } + if (indexType != null) { + indexData.setIndexType(indexType.getValue()); + } + if (tablespace != null) { + indexData.setTablespace(tablespace); + } + parseAppliesToClause(indexDataEntry, indexData); + tableEntry.addIndexData(indexData); + } + } + } + + public void parseAppliesToClause(Element element, IndexElement indexData) { + List<Element> appliesToList = Jaxp.getChildDirects(element, AppliesToClause.APPLIES_TO_TAG); + for (Element appliesToElement : appliesToList) { + String idString = appliesToElement.getAttribute(AppliesToEntries.id.name()); + String sortString = appliesToElement.getAttribute(AppliesToEntries.sort.name()); + if (idString.length() > 0) { + OrderType orderType = OrderType.Undefined; + if (sortString.equalsIgnoreCase("Ascending")) { + orderType = OrderType.Ascending; + } else if (sortString.equalsIgnoreCase("Descending")) { + orderType = OrderType.Descending; + } + indexData.addAppliesTo(idString, orderType); + } + } + } + + public SchemaData parseFromInputStream(InputStream configFile) throws Exception { + Document document = Jaxp.readXmlDocument(configFile); + SchemaData schemaData = new SchemaData(); + List<Element> elements = Jaxp.getChildDirects(document.getDocumentElement(), TableTags.Table.name()); + for (Element element : elements) { + + TableElement tableEntry = new TableElement(); + + parseTableDescription(element, tableEntry); + parseColumnEntries(element, tableEntry); + parseConstraintEntries(element, tableEntry); + parseIndexDataEntries(element, tableEntry); + + schemaData.addTableDefinition(tableEntry); + } + return schemaData; + } + + public void parseFromSchemaProvider(IOseeSchemaProvider schemaProvider, Map<String, SchemaData> schemas) { + for (IOseeSchemaResource schemaResource : schemaProvider.getSchemaResources()) { + SchemaData schemaData; + InputStream inputStream = null; + try { + inputStream = new BufferedInputStream(schemaResource.getContent()); + schemaData = parseFromInputStream(inputStream); + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + String schemaAddress = table.getSchema(); + + SchemaData schema = null; + if (!schemas.containsKey(schemaAddress)) { + schema = new SchemaData(); + schemas.put(schemaAddress, schema); + } else { + schema = schemas.get(schemaAddress); + } + schema.addTableDefinition(table); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + Lib.close(inputStream); + } + } + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/TableElement.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/TableElement.java new file mode 100644 index 00000000000..a6ecf69933a --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/data/TableElement.java @@ -0,0 +1,243 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + + +/** + * @author Roberto E. Escobar + */ +public class TableElement implements Xmlizable { + + public enum TableTags{ + Table, ColumnInfo, Row; + } + + public enum TableSections { + Column, Constraint, Index; + }; + + public enum TableDescriptionFields { + name, schema, backupData, importData, importFrom, tablespace; + }; + + public enum ColumnFields { + id, type, limits, identity, defaultValue;; + }; + + private final Map<TableDescriptionFields, String> tableDescription; + private final Map<String, ColumnMetadata> columns; + private final List<ConstraintElement> constraints; + private final List<ForeignKey> foreignKeys; + private final List<IndexElement> indices; + + public TableElement() { + this.tableDescription = new HashMap<TableDescriptionFields, String>(); + this.columns = new HashMap<String, ColumnMetadata>(); + this.constraints = new ArrayList<ConstraintElement>(); + this.foreignKeys = new ArrayList<ForeignKey>(); + this.indices = new ArrayList<IndexElement>(); + } + + public void addColumn(ColumnMetadata column) { + this.columns.put(column.getId(), column); + } + + public void addConstraint(ConstraintElement constraint) { + if(constraint instanceof ForeignKey){ + foreignKeys.add((ForeignKey)constraint); + } else { + constraints.add(constraint); + } + } + + public void addIndexData(IndexElement indexData){ + indices.add(indexData); + } + + public String getSchema() { + return this.tableDescription.get(TableDescriptionFields.schema); + } + + public String getName() { + return this.tableDescription.get(TableDescriptionFields.name); + } + + public boolean isBackupDataSet(){ + if(this.tableDescription.containsKey(TableDescriptionFields.backupData)){ + return Boolean.parseBoolean(this.tableDescription.get(TableDescriptionFields.backupData)); + } + return false; + } + + public boolean isImportDataSet(){ + if(this.tableDescription.containsKey(TableDescriptionFields.importData)){ + return Boolean.parseBoolean(this.tableDescription.get(TableDescriptionFields.importData)); + } + return false; + } + + public String getImportFrom(){ + if(this.tableDescription.containsKey(TableDescriptionFields.importFrom)){ + return this.tableDescription.get(TableDescriptionFields.importFrom); + } + return null; + } + + public void addTableDescription(TableDescriptionFields field, String value){ + if(!field.equals(TableDescriptionFields.importFrom)){ + value = value.toUpperCase(); + } + value = value.trim(); + this.tableDescription.put(field, value); + } + + public Map<String, ColumnMetadata> getColumns(){ + return this.columns; + } + + public Map<TableDescriptionFields, String> getDescription(){ + return this.tableDescription; + } + + public boolean hasForeignKey(){ + return foreignKeys.size() > 0; + } + + public String getFullyQualifiedTableName(){ + if(getSchema()==null) { + return getName(); + } else { + return getSchema() + "." + getName(); + } + } + + public List<ConstraintElement> getConstraints(){ + return constraints; + } + + public List<ForeignKey> getForeignKeyConstraints(){ + return foreignKeys; + } + + public List<IndexElement> getIndexData(){ + return indices; + } + + @Override + public String toString(){ + StringBuilder toReturn = new StringBuilder(); + toReturn.append(" Table : \n"); + Set<TableDescriptionFields> keys = tableDescription.keySet(); + for(TableDescriptionFields key : keys){ + toReturn.append(" \t" + key.toString() + ": " + tableDescription.get(key)); + } + toReturn.append("\n"); + int count = 0; + Set<String> columnKeys = columns.keySet(); + for(String key : columnKeys){ + toReturn.append("\t[" + ++count + "] " + columns.get(key).toString() + "\n"); + } + count = 0; + for(ConstraintElement constraint : constraints){ + toReturn.append("\t[" + ++count + "] " + constraint.toString() + "\n"); + } + for(ForeignKey fkeys : foreignKeys){ + toReturn.append("\t[" + ++count + "] " + fkeys.toString() + "\n"); + } + count = 0; + for(IndexElement iData : indices){ + toReturn.append("\t[" + ++count + "] " + iData.toString() + "\n"); + } + return toReturn.toString(); + } + + /** + * @param doc The XML document we're creating the XML for + * @return The XML Element corresponding to this + */ + public Element toXml(Document doc) { + Element tableElement = doc.createElement(TableTags.Table.name()); + for(TableDescriptionFields key : tableDescription.keySet()){ + tableElement.setAttribute(key.toString(), tableDescription.get(key)); + } + for(String key : columns.keySet()) { + tableElement.appendChild(columns.get(key).toXml(doc)); + } + for(ConstraintElement constraint : constraints){ + tableElement.appendChild(constraint.toXml(doc)); + } + for(ForeignKey constraint : foreignKeys){ + tableElement.appendChild(constraint.toXml(doc)); + } + for(IndexElement iData : indices){ + tableElement.appendChild(iData.toXml(doc)); + } + return tableElement; + } + + public Set<String> getTableDependency(){ + Set<String> dependency = new TreeSet<String>(); + for(ForeignKey fk : foreignKeys){ + Set<String> refTables = fk.getReferencedTables(); + for(String tableName : refTables){ + dependency.add(tableName); + } + } + return dependency; + } + + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof TableElement == false) { + return false; + } + if (this == otherObject) { + return true; + } + TableElement that = (TableElement) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)) + .append(this.tableDescription, that.getDescription()) + .append(this.columns, that.getColumns()) + .append(this.constraints, that.getConstraints()) + .append(this.foreignKeys, that.getForeignKeyConstraints()) + .append(this.indices, that.getIndexData()) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(79, 17).append(tableDescription).append(columns) + .append(constraints).append(foreignKeys).append(indices).toHashCode(); + } + + public String getTablespace() { + String toReturn = getDescription().get(TableDescriptionFields.tablespace); + return Strings.isValid(toReturn) ? toReturn : ""; + } + + public void setTablespace(String value){ + getDescription().put(TableDescriptionFields.tablespace, value); + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/BackupTableDataOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/BackupTableDataOperation.java new file mode 100644 index 00000000000..a9869af0c62 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/BackupTableDataOperation.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.File; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; + +public class BackupTableDataOperation extends AbstractOperation { + private final File backupDirectory; + private final Set<String> schemas; + private final Map<String, SchemaData> userSpecifiedConfig; + private final Map<String, SchemaData> currentDatabaseConfig; + private final IOseeDatabaseServiceProvider provider; + + public BackupTableDataOperation(IOseeDatabaseServiceProvider provider, String backupDirPath, Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Map<String, SchemaData> currentDatabaseConfig) { + super("Backup Table Data", Activator.PLUGIN_ID); + this.provider = provider; + this.schemas = schemas; + this.userSpecifiedConfig = userSpecifiedConfig; + this.currentDatabaseConfig = currentDatabaseConfig; + this.backupDirectory = new File("BackupDirectory"); + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + Set<String> dataToBackup = getTablesToBackup(); + if (dataToBackup.size() > 0) { + System.out.println(dataToBackup.toString().replaceAll(", ", "\n")); + clearBackupDirectory(); + DatabaseDataExtractor dbDataExtractor = new DatabaseDataExtractor(provider, schemas, backupDirectory); + Set<String> backupTables = dataToBackup; + for (String backupTable : backupTables) { + dbDataExtractor.addTableNameToExtract(backupTable); + } + doSubWork(dbDataExtractor, monitor, 0.90); + dbDataExtractor.waitForWorkerThreads(); + } + } + + private Set<String> getTablesToBackup() { + Set<String> backupTables = new TreeSet<String>(); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + for (String key : userSchemas) { + // Backup data only if data exists in the current database + if (currentDatabaseConfig.containsKey(key)) { + SchemaData schemaDataInDb = currentDatabaseConfig.get(key); + Map<String, TableElement> currentDbTableMap = schemaDataInDb.getTableMap(); + Set<String> currentDbTableNames = currentDbTableMap.keySet(); + + SchemaData schemaData = userSpecifiedConfig.get(key); + Set<String> tableNamesToBackup = schemaData.getTablesToBackup(); + for (String tableName : tableNamesToBackup) { + // Check that table we want to backup exists in the database + // before we add it to the list + if (currentDbTableNames.contains(tableName)) { + backupTables.add(tableName); + } else { + System.out.println("Table doesn't exist in Db. Unable to backup [" + tableName + "]"); + } + } + } else { + System.out.println("Schema doesn't exist in Db. Unable to backup tables from schema [" + key + "]"); + } + } + return backupTables; + } + + private void clearBackupDirectory() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + File[] fileList = backupDirectory.listFiles(); + for (File fileToDelete : fileList) { + fileToDelete.delete(); + } + backupDirectory.delete(); + backupDirectory.mkdirs(); + } + } + +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/CreateSchemaOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/CreateSchemaOperation.java new file mode 100644 index 00000000000..c05006d8e7f --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/CreateSchemaOperation.java @@ -0,0 +1,58 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.operations;
+
+import java.sql.DatabaseMetaData;
+import java.util.Map;
+import java.util.Set;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData;
+import org.eclipse.osee.framework.core.datastore.schema.sql.SchemaSqlUtil;
+import org.eclipse.osee.framework.core.datastore.schema.sql.SqlFactory;
+import org.eclipse.osee.framework.core.datastore.schema.sql.SqlManager;
+import org.eclipse.osee.framework.core.exception.OseeCoreException;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+import org.eclipse.osee.framework.database.core.AbstractDbTxOperation;
+import org.eclipse.osee.framework.database.core.OseeConnection;
+import org.eclipse.osee.framework.database.core.SupportedDatabase;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class CreateSchemaOperation extends AbstractDbTxOperation {
+ private final Map<String, SchemaData> userSchema;
+ private final Map<String, SchemaData> dbSchema;
+
+ public CreateSchemaOperation(IOseeDatabaseServiceProvider provider, Map<String, SchemaData> userSchema, Map<String, SchemaData> dbSchema) {
+ super(provider, "Create Schema", Activator.PLUGIN_ID);
+ this.userSchema = userSchema;
+ this.dbSchema = dbSchema;
+ }
+
+ @Override
+ protected void doTxWork(IProgressMonitor monitor, OseeConnection connection) throws OseeCoreException {
+ DatabaseMetaData metaData = connection.getMetaData();
+ SqlManager sqlManager = SqlFactory.getSqlManager(metaData);
+ SchemaSqlUtil dbInit = new SchemaSqlUtil(sqlManager);
+
+ Set<String> schemas = userSchema.keySet();
+ dbInit.dropIndices(schemas, userSchema, dbSchema);
+ dbInit.dropTables(schemas, userSchema, dbSchema);
+ if (SupportedDatabase.isDatabaseType(metaData, SupportedDatabase.postgresql)) {
+ dbInit.dropSchema(schemas);
+ dbInit.createSchema(schemas);
+ }
+ dbInit.addTables(schemas, userSchema);
+ dbInit.addIndices(schemas, userSchema);
+ }
+
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataExtractor.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataExtractor.java new file mode 100644 index 00000000000..106fcd70b13 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataExtractor.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableTags; +import org.eclipse.osee.framework.core.exception.OseeDataStoreException; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; +import org.eclipse.osee.framework.database.core.IOseeStatement; +import org.eclipse.osee.framework.database.core.SQL3DataType; +import org.eclipse.osee.framework.database.core.SupportedDatabase; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseDataExtractor extends AbstractOperation { + + private static final String SQL_WILD_QUERY = "SELECT * FROM "; + private final Set<String> schemas; + private final File directory; + private final List<Thread> workerThreads; + private final Set<String> extractTables; + + private class ColumnInfo { + String name; + SQL3DataType type; + } + + private final IOseeDatabaseServiceProvider provider; + + public DatabaseDataExtractor(IOseeDatabaseServiceProvider provider, Set<String> schemas, File directory) throws OseeDataStoreException { + super("Extract Database Data", Activator.PLUGIN_ID); + this.provider = provider; + this.schemas = schemas; + this.directory = directory; + this.workerThreads = new ArrayList<Thread>(); + this.extractTables = new TreeSet<String>(); + } + + public void addTableNameToExtract(String fullyQualifiedTableName) { + this.extractTables.add(fullyQualifiedTableName); + } + + public void clearFilter() { + this.extractTables.clear(); + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + FileUtility.setupDirectoryForWrite(directory); + + Map<String, SchemaData> schemaDataMap = new HashMap<String, SchemaData>(); + ExtractDatabaseSchemaOperation operation = new ExtractDatabaseSchemaOperation(provider, schemas, schemaDataMap); + doSubWork(operation, monitor, 0.20); + + Set<String> schemaKeys = schemaDataMap.keySet(); + for (String schema : schemaKeys) { + SchemaData schemaData = schemaDataMap.get(schema); + + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + + boolean extract = true; + // only extract items in filter since filter was set with data + if (this.extractTables != null && this.extractTables.size() > 0) { + extract = extractTables.contains(table.getFullyQualifiedTableName()); + } + + if (extract) { + DataExtractorThread workerThread = new DataExtractorThread(table); + workerThreads.add(workerThread); + workerThread.start(); + } + } + } + } + + private class DataExtractorThread extends Thread { + private final TableElement table; + + public DataExtractorThread(TableElement table) { + this.table = table; + setName(table.getName() + " Extractor"); + } + + @Override + public void run() { + IOseeStatement chStmt = null; + OutputStream outputStream = null; + try { + chStmt = provider.getOseeDatabaseService().getStatement(); + String fileName = table.getFullyQualifiedTableName() + FileUtility.DB_DATA_EXTENSION; + outputStream = new BufferedOutputStream(new FileOutputStream(new File(directory, fileName))); + + try { + chStmt.runPreparedQuery(SQL_WILD_QUERY + table.getFullyQualifiedTableName()); + } catch (OseeDataStoreException ex) { + chStmt.runPreparedQuery(SQL_WILD_QUERY + table.getName()); + } + + buildXml(chStmt, table, outputStream); + } catch (Exception ex) { + OseeLog.log(Activator.class, Level.SEVERE, + "Error Processing Table [ " + table.getSchema() + "." + table.getName() + " ] Data ", ex); + } finally { + Lib.close(chStmt); + Lib.close(outputStream); + } + } + } + + public void waitForWorkerThreads() { + for (Thread worker : workerThreads) { + try { + worker.join(); + } catch (InterruptedException ex) { + OseeLog.log(Activator.class, Level.SEVERE, "Thread [" + worker.getName() + "] was Interrupted. ", ex); + } + } + } + + private void buildXml(IOseeStatement chStmt, TableElement table, OutputStream outputStream) throws Exception { + ArrayList<ColumnInfo> columns = new ArrayList<ColumnInfo>(); + int numberOfColumns = chStmt.getColumnCount(); + for (int index = 1; index <= numberOfColumns; index++) { + ColumnInfo columnInfo = new ColumnInfo(); + columnInfo.name = chStmt.getColumnName(index); + columnInfo.name = columnInfo.name.toUpperCase(); + + int dataType = chStmt.getColumnType(index); + if (chStmt.isDatabaseType(SupportedDatabase.foxpro)) { + if (dataType == Types.CHAR) { + dataType = Types.VARCHAR; + } + } + columnInfo.type = SQL3DataType.get(dataType); + columns.add(columnInfo); + } + + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + XMLStreamWriter writer = factory.createXMLStreamWriter(outputStream); + writer.writeStartDocument("UTF-8", "1.0"); + writer.writeStartElement(TableTags.Table.name()); + writer.writeAttribute(TableDescriptionFields.schema.name(), table.getSchema()); + writer.writeAttribute(TableDescriptionFields.name.name(), table.getName()); + + for (ColumnInfo info : columns) { + writer.writeStartElement(TableTags.ColumnInfo.name()); + writer.writeAttribute(ColumnFields.id.name(), info.name); + writer.writeAttribute(ColumnFields.type.name(), info.type.name()); + writer.writeEndElement(); + } + + while (chStmt.next()) { + writer.writeStartElement(TableTags.Row.name()); + for (ColumnInfo column : columns) { + String columnValue; + switch (column.type) { + case BIGINT: + BigDecimal bigD = chStmt.getBigDecimal(column.name); + columnValue = bigD != null ? bigD.toString() : ""; + break; + case DATE: + Date date = chStmt.getDate(column.name); + columnValue = date != null ? date.toString() : ""; + break; + case TIME: + Time time = chStmt.getTime(column.name); + columnValue = time != null ? time.toString() : ""; + break; + case TIMESTAMP: + Timestamp timestamp = chStmt.getTimestamp(column.name); + columnValue = timestamp != null ? timestamp.toString() : ""; + break; + default: + columnValue = chStmt.getString(column.name); + columnValue = handleSpecialCharacters(columnValue); + break; + } + writer.writeAttribute(column.name, (columnValue != null ? columnValue : "")); + } + writer.writeEndElement(); + } + writer.writeEndElement(); + writer.writeEndDocument(); + writer.flush(); + } + + private String handleSpecialCharacters(String value) { + // \0 An ASCII 0 (NUL) character. + // '' A single quote (�'�) character. + // \b A backspace character. + // \n A newline (linefeed) character. + // \r A carriage return character. + // \t A tab character. + // \Z ASCII 26 (Control-Z). See note following the table. + + if (value != null) { + + value = value.replaceAll("\0", ""); + value = value.replaceAll("'", "''"); + // value = value.replaceAll("\"", "\\\\\""); No need to do this. + Pattern pattern = + Pattern.compile("[^" + "a-zA-Z0-9" + "!@#$%\\^&*\\(\\)" + "+ _.-=" + "\'\"<>{}\\[\\]|:;,\n\r\t\b?/`~\\\\]+"); + Matcher matcher = pattern.matcher(value); + + while (matcher.find()) { + // System.out.println("Matcher: [" + matcher.group() + "]"); + value = value.replace(matcher.group(), ""); + } + } + return value; + } + +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataImporter.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataImporter.java new file mode 100644 index 00000000000..41db0cac92a --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/DatabaseDataImporter.java @@ -0,0 +1,255 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.operations;
+
+import java.io.File;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.logging.Level;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnDbData;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableDescriptionFields;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableTags;
+import org.eclipse.osee.framework.core.datastore.schema.sql.SqlManager;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.logging.OseeLog;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DatabaseDataImporter {
+ private final File directory;
+ private final SqlManager sqlManager;
+ private List<String> tableOrder;
+ private String schemaToImportTo;
+ private final Set<String> tableFilter;
+
+ private class TableData extends TableElement {
+ private final List<List<ColumnDbData>> rowData;
+
+ public TableData() {
+ rowData = new ArrayList<List<ColumnDbData>>();
+ }
+
+ public void addRow(List<ColumnDbData> row) {
+ rowData.add(row);
+ }
+
+ public List<List<ColumnDbData>> getRows() {
+ return rowData;
+ }
+ }
+
+ public DatabaseDataImporter(File directory, SqlManager sqlManager) {
+ this.directory = directory;
+ this.sqlManager = sqlManager;
+ this.tableFilter = new TreeSet<String>();
+ }
+
+ public void setImportOrder(List<String> tableOrder) {
+ this.tableOrder = tableOrder;
+ }
+
+ public void setSchemaToImportTo(String schema) {
+ this.schemaToImportTo = schema;
+ }
+
+ public void addToTableFilter(String fullyQualifiedTableName) {
+ this.tableFilter.add(fullyQualifiedTableName);
+ }
+
+ public void clearTableFilter() {
+ this.tableFilter.clear();
+ }
+
+ public List<File> orderFilesByImportOrder(Map<String, File> toOrder) {
+ List<File> orderedSet = new ArrayList<File>();
+ if (tableOrder != null && tableOrder.size() != 0) {
+ for (String tableName : tableOrder) {
+ String fileName = tableName + FileUtility.DB_DATA_EXTENSION;
+ File file = toOrder.get(fileName);
+ if (file != null) {
+ orderedSet.add(file);
+ }
+ }
+ } else {
+ Set<String> keys = toOrder.keySet();
+ for (String key : keys) {
+ orderedSet.add(toOrder.get(key));
+ }
+ }
+ return orderedSet;
+ }
+
+ public Map<String, File> filterDataToImport(Map<String, File> toProcess) {
+ Map<String, File> filteredList = new HashMap<String, File>();
+ if (tableFilter != null && tableFilter.size() != 0) {
+ for (String tableName : tableFilter) {
+ String fileName = tableName + FileUtility.DB_DATA_EXTENSION;
+ File file = toProcess.get(fileName);
+ if (file != null) {
+ filteredList.put(fileName, file);
+ }
+ }
+ } else {
+ return toProcess;
+ }
+ return filteredList;
+ }
+
+ public void importDataIntoDatabase() {
+ if (FileUtility.isValidDirectory(directory)) {
+ Map<String, File> filesToProcess = getFilesToProcess();
+ Map<String, File> filteredFiles = filterDataToImport(filesToProcess);
+ List<File> files = orderFilesByImportOrder(filteredFiles);
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder;
+ Document document;
+ for (File file : files) {
+ try {
+ builder = factory.newDocumentBuilder();
+ document = builder.parse(file);
+ processData(parseXMLDbDataFile(document));
+ } catch (ParserConfigurationException ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, "Unable to Parse File. ", ex);
+ } catch (Exception ex) {
+ OseeLog.log(Activator.class, Level.SEVERE, "Exception: \n", ex);
+ }
+ }
+ }
+ }
+
+ private Map<String, File> getFilesToProcess() {
+ Map<String, File> toReturn = new HashMap<String, File>();
+ List<File> files = FileUtility.getDBDataFileList(directory);
+ for (File fileName : files) {
+ toReturn.put(fileName.getName(), new File(directory + File.separator + fileName.getName()));
+ }
+ return toReturn;
+ }
+
+ private void processData(List<TableData> tables) throws OseeDataStoreException, ParseException {
+ if (tables.size() != 0) {
+ for (TableData tableData : tables) {
+ OseeLog.log(Activator.class, Level.INFO, "Populating: [ " + tableData.getFullyQualifiedTableName() + "]\n");
+ List<List<ColumnDbData>> rows = tableData.getRows();
+ if (!rows.isEmpty()) {
+ for (List<ColumnDbData> rowData : rows) {
+ sqlManager.insertData(rowData, tableData);
+ }
+ }
+ }
+ }
+ }
+
+ private void parseColumnMetadata(Element tableElement, TableData tableData) {
+ NodeList columnElements = tableElement.getElementsByTagName(TableTags.ColumnInfo.name());
+ if (columnElements != null) {
+ for (int index = 0; index < columnElements.getLength(); index++) {
+ Element columnElement = (Element) columnElements.item(index);
+ if (columnElement != null) {
+
+ NamedNodeMap attributeMap = columnElement.getAttributes();
+ if (attributeMap != null && attributeMap.getLength() != 0) {
+ ColumnMetadata columnMetaData = new ColumnMetadata("");
+ for (int attributeIndex = 0; attributeIndex < attributeMap.getLength(); attributeIndex++) {
+ Node node = attributeMap.item(attributeIndex);
+ String nodeName = node.getNodeName();
+ String nodeValue = node.getTextContent();
+ if (nodeName != null && !nodeName.equals("")) {
+ columnMetaData.addColumnField(ColumnFields.valueOf(nodeName),
+ (nodeValue != null ? nodeValue : ""));
+ }
+ }
+ tableData.addColumn(columnMetaData);
+ }
+ }
+ }
+ }
+ }
+
+ private void parseRowInformation(Element tableElement, TableData tableData) {
+ NodeList rowElements = tableElement.getElementsByTagName(TableTags.Row.name());
+ if (rowElements != null) {
+ for (int rowIndex = 0; rowIndex < rowElements.getLength(); rowIndex++) {
+ Element row = (Element) rowElements.item(rowIndex);
+ if (row != null) {
+ NamedNodeMap attributeMap = row.getAttributes();
+ if (attributeMap != null && attributeMap.getLength() != 0) {
+ List<ColumnDbData> rowData = new ArrayList<ColumnDbData>();
+ tableData.addRow(rowData);
+ for (int attributeIndex = 0; attributeIndex < attributeMap.getLength(); attributeIndex++) {
+ Node node = attributeMap.item(attributeIndex);
+ String nodeName = node.getNodeName();
+ String nodeValue = node.getTextContent();
+ if (nodeName != null && !nodeName.equals("")) {
+ rowData.add(new ColumnDbData(nodeName, (nodeValue != null ? nodeValue : "")));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private List<TableData> parseXMLDbDataFile(Document document) {
+ NodeList tableElements = document.getElementsByTagName(TableTags.Table.name());
+ List<TableData> tables = new ArrayList<TableData>();
+ for (int index = 0; index < tableElements.getLength(); index++) {
+ Element tableXmlElement = (Element) tableElements.item(index);
+ if (tableXmlElement != null) {
+ NamedNodeMap map = tableXmlElement.getAttributes();
+ if (map != null && map.getLength() != 0) {
+ Node tableName = map.getNamedItem(TableDescriptionFields.name.name());
+ Node tableAddress = map.getNamedItem(TableDescriptionFields.schema.name());
+ String tableNameString = "";
+ String tableAddressString = "";
+ if (tableName != null) {
+ tableNameString = tableName.getTextContent();
+ }
+ if (tableAddress != null) {
+ tableAddressString = tableAddress.getTextContent();
+ }
+
+ if (tableNameString != null && !tableNameString.equals("") && tableAddressString != null && !tableAddressString.equals("")) {
+ TableData tableData = new TableData();
+ tableData.addTableDescription(TableDescriptionFields.name, tableNameString);
+ if (this.schemaToImportTo != null && !this.schemaToImportTo.equals("")) {
+ tableData.addTableDescription(TableDescriptionFields.schema, schemaToImportTo);
+ } else {
+ tableData.addTableDescription(TableDescriptionFields.schema, tableAddressString);
+ }
+ parseRowInformation(tableXmlElement, tableData);
+ parseColumnMetadata(tableXmlElement, tableData);
+ tables.add(tableData);
+ }
+ }
+ }
+ }
+ return tables;
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ExtractDatabaseSchemaOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ExtractDatabaseSchemaOperation.java new file mode 100644 index 00000000000..f18f8e2b8cc --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ExtractDatabaseSchemaOperation.java @@ -0,0 +1,487 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause; +import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata; +import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement; +import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintFactory; +import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintTypes; +import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey; +import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.IOseeDatabaseService; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; +import org.eclipse.osee.framework.database.core.OseeConnection; +import org.eclipse.osee.framework.database.core.SQL3DataType; +import org.eclipse.osee.framework.database.core.SupportedDatabase; + +/** + * @author Roberto E. Escobar + */ +public class ExtractDatabaseSchemaOperation extends AbstractOperation { + private static final String DEFAULT_FILTER = "BIN.*"; + + private DatabaseMetaData dbData; + private String dbName; + private String dbVersion; + private final Map<String, SchemaData> database; + private final List<String> filter; + private final Set<String> tablesToExtract; + private final Set<String> schemas; + private final IOseeDatabaseServiceProvider provider; + + public ExtractDatabaseSchemaOperation(IOseeDatabaseServiceProvider provider, Set<String> schemas, Map<String, SchemaData> schemaData) { + super("Extract Database Schema", Activator.PLUGIN_ID); + this.provider = provider; + this.schemas = schemas; + this.database = schemaData; + this.filter = new ArrayList<String>(); + filter.add(DEFAULT_FILTER); + this.tablesToExtract = new TreeSet<String>(); + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + IOseeDatabaseService service = provider.getOseeDatabaseService(); + OseeConnection connection = service.getConnection(); + try { + this.dbData = connection.getMetaData(); + + this.dbName = dbData.getDatabaseProductName(); + this.dbVersion = dbData.getDatabaseProductVersion(); + + for (String schema : schemas) { + SchemaData dbTables = getTableInformation(schema); + database.put(schema, dbTables); + } + } finally { + connection.close(); + } + } + + public void addToFilter(String value) { + filter.add(value); + } + + // private Set<String> getAllSchemas() throws SQLException { + // ResultSet schemaResults = dbData.getSchemas(); + // Set<String> schemaSet = new TreeSet<String>(); + // + // while (schemaResults.next()) { + // String schema = schemaResults.getString("TABLE_SCHEM"); + // if (schema != null && !schema.equals("")) { + // schemaSet.add(schema); + // } + // } + // schemaResults.close(); + // return schemaSet; + // } + + // /** + // * Writes the XML files in the directory specified. + // * + // * @param directory The directory tow write the XML files. + // * @throws IOException + // */ + // public void writeToFile(File directory) throws IOException { + // FileUtility.setupDirectoryForWrite(directory); + // Set<String> keys = database.keySet(); + // for (String schema : keys) { + // SchemaData tableData = database.get(schema); + // File xmlFile = new File(directory.getAbsolutePath() + File.separator + schema + FileUtility.SCHEMA_EXTENSION); + // try { + // Jaxp.writeXmlDocument(tableData.getXmlDocument(), xmlFile); + // } catch (Exception ex) { + // OseeLog.log(Activator.class, Level.SEVERE, ex); + // } + // } + // } + + @Override + public String toString() { + StringBuilder buffer = new StringBuilder(); + Set<String> keys = database.keySet(); + for (String schema : keys) { + SchemaData tableData = database.get(schema); + buffer.append(" Schema: \n"); + buffer.append(schema); + buffer.append("\n"); + buffer.append(tableData.toString()); + } + return String.format("Name: [%s]\tVer: [%s]\n%s", dbName, dbVersion, buffer); + } + + private boolean isFiltered(String value) { + for (String filterExpression : filter) { + Pattern searchPattern = Pattern.compile(filterExpression, Pattern.DOTALL); + Matcher matcher = searchPattern.matcher(value); + if (matcher.find()) { + return true; + } + } + return false; + } + + public void addTableToExtract(String fullyqualifiedTableName) { + this.tablesToExtract.add(fullyqualifiedTableName); + } + + public void clearTableFilter() { + tablesToExtract.clear(); + } + + private SchemaData getTableInformation(String schemaPattern) throws Exception { + SchemaData dbTables = new SchemaData(); + ResultSet tables = null; + tables = dbData.getTables(null, null, null, new String[] {"TABLE"}); + + while (tables.next()) { + String tableName = tables.getString("TABLE_NAME").toUpperCase(); + String schemaName = tables.getString("TABLE_SCHEM"); + if (tableName != null && !isFiltered(tableName) && schemaName.equalsIgnoreCase(schemaPattern)) { + boolean extract = true; + if (this.tablesToExtract != null && this.tablesToExtract.size() > 0) { + extract = tablesToExtract.contains(schemaPattern + "." + tableName); + } + + if (extract) { + TableElement tableEntry = new TableElement(); + tableEntry.addTableDescription(TableDescriptionFields.name, tableName); + tableEntry.addTableDescription(TableDescriptionFields.schema, schemaName); + getColumnInformation(tableEntry); + getColumnPrimaryKey(tableEntry); + + if (!(SupportedDatabase.isDatabaseType(dbData, SupportedDatabase.foxpro) || SupportedDatabase.isDatabaseType( + dbData, SupportedDatabase.postgresql))) { + getColumnForeignKey(tableEntry); + } + getIndexInfo(tableEntry); + dbTables.addTableDefinition(tableEntry); + } + } + } + tables.close(); + return dbTables; + } + + private void getColumnInformation(TableElement aTable) throws Exception { + ResultSet columns = null; + try { + columns = dbData.getColumns(null, aTable.getSchema(), aTable.getName(), null); + } catch (SQLException ex) { + columns = dbData.getColumns(null, null, aTable.getName(), null); + } + while (columns.next()) { + String id = columns.getString("COLUMN_NAME"); + id = id.toUpperCase(); + ColumnMetadata column = new ColumnMetadata(id); + + int dataType = columns.getInt("DATA_TYPE"); + if (SupportedDatabase.isDatabaseType(dbData, SupportedDatabase.foxpro)) { + if (dataType == Types.CHAR) { + dataType = Types.VARCHAR; + } + } + String dataTypeName = SQL3DataType.get(dataType).name(); + column.addColumnField(ColumnFields.type, dataTypeName); + + String defaultValue = ""; + int defaultType = columns.getInt("NULLABLE"); + switch (defaultType) { + case java.sql.DatabaseMetaData.columnNoNulls: + defaultValue = "not null"; + break; + case java.sql.DatabaseMetaData.columnNullable: + // Dont specify if Null - Let DB Decide. + defaultValue = ""; + break; + case java.sql.DatabaseMetaData.columnNullableUnknown: + default: + // Since unknown then don't specify + defaultValue = ""; + break; + } + if (!defaultValue.equals("")) { + column.addColumnField(ColumnFields.defaultValue, defaultValue); + } + + if (!SupportedDatabase.isDatabaseType(dbData, SupportedDatabase.foxpro)) { + // int dataType = columns.getInt("DATA_TYPE"); + switch (dataType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + String limits = columns.getString("COLUMN_SIZE"); + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + break; + case java.sql.Types.DECIMAL: + case java.sql.Types.NUMERIC: + limits = columns.getString("COLUMN_SIZE"); + String decimal = columns.getString("DECIMAL_DIGITS"); + if (decimal != null && !decimal.equals("")) { + if (limits != null && !limits.equals("")) { + limits += "," + decimal; + } + } + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + default: + break; + } + } else { + switch (dataType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + String limits = "255"; + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + break; + default: + break; + } + } + aTable.addColumn(column); + } + columns.close(); + } + + private void getColumnPrimaryKey(TableElement aTable) throws SQLException { + ResultSet primaryKeys = null; + try { + primaryKeys = dbData.getPrimaryKeys(null, aTable.getSchema(), aTable.getName()); + } catch (SQLException ex) { + primaryKeys = dbData.getPrimaryKeys(null, null, aTable.getName()); + } + Map<String, Set<String>> constraintKeyMap = new HashMap<String, Set<String>>(); + + while (primaryKeys.next()) { + String column = primaryKeys.getString("COLUMN_NAME"); + String keyId = primaryKeys.getString("PK_NAME"); + + if (keyId == null || keyId.equals("")) { + keyId = column + "_PK"; + } + + if (!constraintKeyMap.containsKey(keyId)) { + Set<String> set = new TreeSet<String>(); + set.add(column); + constraintKeyMap.put(keyId, set); + } else { + Set<String> set = constraintKeyMap.get(keyId); + if (!set.contains(column)) { + set.add(column); + } + } + } + + Set<String> keys = constraintKeyMap.keySet(); + for (String pk : keys) { + ConstraintElement constraint = + ConstraintFactory.getConstraint(ConstraintTypes.PRIMARY_KEY, aTable.getSchema(), pk, false); + Set<String> columnSet = constraintKeyMap.get(pk); + for (String column : columnSet) { + constraint.addColumn(column); + } + aTable.addConstraint(constraint); + } + primaryKeys.close(); + } + + private void getColumnForeignKey(TableElement aTable) throws SQLException { + ResultSet importedKeys = dbData.getImportedKeys(null, aTable.getSchema(), aTable.getName()); + + while (importedKeys.next()) { + + String appliesToColumnId = importedKeys.getString("FKCOLUMN_NAME"); + String fkeyId = importedKeys.getString("FK_NAME"); + String fKeyAddress = importedKeys.getString("FKTABLE_SCHEM"); + + String refersToTable = importedKeys.getString("PKTABLE_NAME"); + String refersToTableAddress = importedKeys.getString("PKTABLE_SCHEM"); + String referencesColumn = importedKeys.getString("PKCOLUMN_NAME"); + + OnDeleteEnum onDeleteAction = OnDeleteEnum.UNSPECIFIED; + String onDeleteRule = importedKeys.getString("DELETE_RULE"); + if (onDeleteRule != null && !onDeleteRule.equals("")) { + // System.out.println("onDelete: " + onDeleteRule); + int type = Integer.parseInt(onDeleteRule); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyNoAction: + onDeleteAction = OnDeleteEnum.NO_ACTION; + break; + case java.sql.DatabaseMetaData.importedKeyRestrict: + onDeleteAction = OnDeleteEnum.RESTRICT; + break; + case java.sql.DatabaseMetaData.importedKeyCascade: + onDeleteAction = OnDeleteEnum.CASCADE; + break; + case java.sql.DatabaseMetaData.importedKeySetNull: + onDeleteAction = OnDeleteEnum.SET_NULL; + break; + case java.sql.DatabaseMetaData.importedKeySetDefault: + default: + onDeleteAction = OnDeleteEnum.UNSPECIFIED; + break; + } + } + + OnUpdateEnum onUpdateAction = OnUpdateEnum.UNSPECIFIED; + String onUpdateRule = importedKeys.getString("UPDATE_RULE"); + if (onUpdateRule != null && !onUpdateRule.equals("")) { + // System.out.println("onUpdate: " + onUpdateRule); + int type = Integer.parseInt(onUpdateRule); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyNoAction: + onUpdateAction = OnUpdateEnum.NO_ACTION; + break; + case java.sql.DatabaseMetaData.importedKeyRestrict: + onUpdateAction = OnUpdateEnum.RESTRICT; + break; + case java.sql.DatabaseMetaData.importedKeyCascade: + case java.sql.DatabaseMetaData.importedKeySetNull: + case java.sql.DatabaseMetaData.importedKeySetDefault: + default: + onUpdateAction = OnUpdateEnum.UNSPECIFIED; + break; + } + } + + boolean deferrable = false; + String deferrabilityId = importedKeys.getString("DEFERRABILITY"); + if (deferrabilityId != null && !deferrabilityId.equals("")) { + int type = Integer.parseInt(deferrabilityId); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyInitiallyDeferred: + case java.sql.DatabaseMetaData.importedKeyInitiallyImmediate: + deferrable = true; + break; + case java.sql.DatabaseMetaData.importedKeyNotDeferrable: + deferrable = false; + break; + default: + deferrable = false; + break; + } + } + + if (fKeyAddress == null || fKeyAddress.equals("")) { + fKeyAddress = aTable.getSchema(); + } + + if (fkeyId == null || fkeyId.equals("")) { + fkeyId = appliesToColumnId + "_FK"; + } + + if (refersToTableAddress == null || refersToTableAddress.equals("")) { + refersToTableAddress = aTable.getSchema(); + } + + ConstraintElement constraint = + ConstraintFactory.getConstraint(ConstraintTypes.FOREIGN_KEY, fKeyAddress, fkeyId, deferrable); + constraint.addColumn(appliesToColumnId); + + ReferenceClause ref = new ReferenceClause(refersToTableAddress, refersToTable); + ref.addColumn(referencesColumn); + + ref.setOnDeleteAction(onDeleteAction); + ref.setOnUpdateAction(onUpdateAction); + + ((ForeignKey) constraint).addReference(ref); + + aTable.addConstraint(constraint); + } + importedKeys.close(); + } + + private void getIndexInfo(TableElement aTable) throws SQLException { + ResultSet indexKeys = dbData.getIndexInfo(null, aTable.getSchema(), aTable.getName(), false, false); + Pattern pattern = Pattern.compile("SQL\\d+"); + + Map<String, Map<Integer, AppliesToClause>> indexMap = new HashMap<String, Map<Integer, AppliesToClause>>(); + + while (indexKeys.next()) { + String indexName = indexKeys.getString("INDEX_NAME"); + + if (indexName != null && indexName.length() > 0) { + Matcher matcher = pattern.matcher(indexName); + if (!matcher.matches()) { + if (indexKeys.getShort("TYPE") == DatabaseMetaData.tableIndexOther) { + + short ordinal = indexKeys.getShort("ORDINAL_POSITION"); + String columnName = indexKeys.getString("COLUMN_NAME"); + + String orderTypeString = indexKeys.getString("ASC_OR_DESC"); + OrderType orderType = OrderType.Undefined; + if (orderTypeString != null) { + if (orderTypeString.equalsIgnoreCase("A")) { + orderType = OrderType.Ascending; + } else if (orderTypeString.equalsIgnoreCase("D")) { + orderType = OrderType.Descending; + } + } + + Map<Integer, AppliesToClause> appliesTo = null; + if (indexMap.containsKey(indexName)) { + appliesTo = indexMap.get(indexName); + } else { + appliesTo = new HashMap<Integer, AppliesToClause>(); + indexMap.put(indexName, appliesTo); + } + appliesTo.put(new Integer(ordinal), new AppliesToClause(columnName, orderType)); + } + } + } + } + for (String indexName : indexMap.keySet()) { + Map<Integer, AppliesToClause> clauseMap = indexMap.get(indexName); + IndexElement element = new IndexElement(indexName); + + Set<Integer> index = clauseMap.keySet(); + Set<Integer> sortedIndex = new TreeSet<Integer>(); + for (Integer val : index) { + sortedIndex.add(val); + } + + for (Integer val : sortedIndex) { + AppliesToClause clause = clauseMap.get(val); + element.addAppliesTo(clause.getColumnName(), clause.getOrderType()); + } + aTable.addIndexData(element); + } + indexKeys.close(); + } +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/FileUtility.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/FileUtility.java new file mode 100644 index 00000000000..a889d941d31 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/FileUtility.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.File; +import java.io.FilenameFilter; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +// TODO: this class has some overlap with methods provided in org.eclipse.osee.framework.jdk.core.Lib +public final class FileUtility { + + public static String SCHEMA_EXTENSION = ".SCHEMA.xml"; + public static String DB_DATA_EXTENSION = ".DATA.xml"; + + private FileUtility() { + + } + + public static boolean isValidDirectory(File directory) { + if (directory != null && directory.exists() && directory.canRead()) { + File[] listOfFiles = directory.listFiles(); + if (listOfFiles.length != 0) { + return true; + } + } + return false; + } + + public static void setupDirectoryForWrite(File directory) { + if (directory.exists() && directory.canWrite()) { + if (!directory.isDirectory()) { + directory.mkdirs(); + } + } else { + directory.mkdirs(); + } + } + + public static List<File> getFileList(File sourceDirectory, final String extension) { + File[] listOfFiles = sourceDirectory.listFiles(new FilenameFilter() { + public boolean accept(File directoryName, String filename) { + return filename.endsWith(extension) && new File(directoryName + File.separator + filename).canRead(); + } + }); + return Arrays.asList(listOfFiles); + } + + public static List<URL> getSchemaFileList(File sourceDirectory) { + List<File> files = getFileList(sourceDirectory, SCHEMA_EXTENSION); + List<URL> streams = new ArrayList<URL>(); + for (File file : files) { + try { + streams.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + return streams; + } + + public static List<File> getDBDataFileList(File sourceDirectory) { + return getFileList(sourceDirectory, DB_DATA_EXTENSION); + } + + public static List<URL> getDBDataFileListInputStream(File sourceDirectory) { + List<File> files = getFileList(sourceDirectory, DB_DATA_EXTENSION); + List<URL> streams = new ArrayList<URL>(); + for (File file : files) { + try { + streams.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + return streams; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ImportDataFromDbServiceOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ImportDataFromDbServiceOperation.java new file mode 100644 index 00000000000..04fedc3ef3f --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/ImportDataFromDbServiceOperation.java @@ -0,0 +1,187 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.data.IDatabaseInfo; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider; +import org.eclipse.osee.framework.database.core.DatabaseInfoManager; +import org.eclipse.osee.framework.jdk.core.util.Strings; + +/** + * @author Roberto E. Escobar + */ +public class ImportDataFromDbServiceOperation extends AbstractOperation { + + private static final File backupDirectory = new File("BackupDirectory"); + + private final Map<String, SchemaData> userSpecifiedConfig; + private final String tableImportSource; + private final IOseeDatabaseServiceProvider provider; + + public ImportDataFromDbServiceOperation(IOseeDatabaseServiceProvider provider, Map<String, SchemaData> userSpecifiedConfig, String tableImportSource) { + super("Import Data from Db Service", Activator.PLUGIN_ID); + this.provider = provider; + this.userSpecifiedConfig = userSpecifiedConfig; + this.tableImportSource = tableImportSource; + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + Set<String> importConnections = getImportConnections(); + for (String importFromDbService : importConnections) { + System.out.println("Import Table Data from Db: " + importFromDbService); + + IDatabaseInfo dbInfo = DatabaseInfoManager.getDataStoreById(importFromDbService); + System.out.println("Gathering information from ..." + importFromDbService); + + String userName = dbInfo.getDatabaseLoginName(); + if (userName != null && !userName.equals("")) { + + Set<String> schemasToGet = new TreeSet<String>(); + schemasToGet.add(userName.toUpperCase()); + + Map<String, Set<String>> dataToImport = getTablesToImport(monitor, userName.toUpperCase(), schemasToGet); + if (dataToImport.size() > 0) { + System.out.println(dataToImport.toString().replaceAll(", ", "\n")); + makeBackupDirectoryIfItDoesntExist(); + + System.out.println("Backing up Files to: " + backupDirectory.getAbsolutePath()); + DatabaseDataExtractor dbDataExtractor = new DatabaseDataExtractor(provider, schemasToGet, backupDirectory); + + Set<String> tablesToImport; + if (importFromDbService.equals(determineDefaultConnection())) { + tablesToImport = dataToImport.get(tableImportSource); + } else { + tablesToImport = dataToImport.get(importFromDbService); + } + + for (String importTable : tablesToImport) { + dbDataExtractor.addTableNameToExtract(importTable); + } + doSubWork(dbDataExtractor, monitor, 0.10); + dbDataExtractor.waitForWorkerThreads(); + + prepareFilesForImport(); + } + } + } + } + + private void prepareFilesForImport() { + Set<String> keys = userSpecifiedConfig.keySet(); + if (keys.size() == 1) { + String userName = ""; + for (String temp : keys) { + userName = temp; + } + List<File> files = FileUtility.getDBDataFileList(backupDirectory); + for (File fileName : files) { + String filename = fileName.getAbsolutePath().toString(); + filename = filename.substring(filename.lastIndexOf(File.separator) + 1, filename.length()); + filename = filename.substring(filename.indexOf(".") + 1, filename.length()); + fileName.renameTo(new File(backupDirectory + File.separator + userName + "." + filename)); + } + } + } + + private String determineDefaultConnection() { + String importFromDbService = System.getProperty(tableImportSource); + if (!Strings.isValid(importFromDbService)) { + importFromDbService = "oracle"; + } + return importFromDbService; + } + + private Set<String> getImportConnections() { + String defaultConnection = determineDefaultConnection(); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + Set<String> connectionsNeeded = new TreeSet<String>(); + for (String key : userSchemas) { + SchemaData schemaDataInUserConfig = userSpecifiedConfig.get(key); + Map<String, Set<String>> tableNamesToImport = schemaDataInUserConfig.getTablesToImport(tableImportSource); + Set<String> keys = tableNamesToImport.keySet(); + for (String connectionString : keys) { + if (connectionString.equals(tableImportSource)) { + connectionsNeeded.add(defaultConnection); + } else { + connectionsNeeded.add(connectionString); + } + } + } + return connectionsNeeded; + } + + public boolean canRun() { + return true; + } + + private Map<String, SchemaData> getAvailableSchemasFromImportDb(IProgressMonitor monitor, Set<String> schemas) throws Exception { + Map<String, SchemaData> schemaMap = new HashMap<String, SchemaData>(); + ExtractDatabaseSchemaOperation schemaExtractor = new ExtractDatabaseSchemaOperation(provider, schemas, schemaMap); + doSubWork(schemaExtractor, monitor, 0.20); + return schemaMap; + } + + private Map<String, Set<String>> getTablesToImport(IProgressMonitor monitor, String userName, Set<String> schemasToGet) throws Exception { + Map<String, SchemaData> currentDbSchemas = getAvailableSchemasFromImportDb(monitor, schemasToGet); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + + SchemaData schemaData = currentDbSchemas.get(userName); + Map<String, TableElement> tableMap = schemaData.getTableMap(); + + Map<String, Set<String>> importTables = new HashMap<String, Set<String>>(); + for (String key : userSchemas) { + SchemaData schemaDataInUserConfig = userSpecifiedConfig.get(key); + Map<String, Set<String>> tableNamesToImport = schemaDataInUserConfig.getTablesToImport(tableImportSource); + + Set<String> keys = tableNamesToImport.keySet(); + for (String importKey : keys) { + Set<String> namesToImport = tableNamesToImport.get(importKey); + + for (String tableName : namesToImport) { + tableName = tableName.replaceAll(key + "\\.", userName + "."); + + if (tableMap.containsKey(tableName)) { + Set<String> tableSet; + if (importTables.containsKey(importKey)) { + tableSet = importTables.get(importKey); + } else { + tableSet = new TreeSet<String>(); + } + tableSet.add(tableName); + importTables.put(importKey, tableSet); + } + } + } + } + return importTables; + } + + private void makeBackupDirectoryIfItDoesntExist() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + return; + } else { + backupDirectory.mkdirs(); + } + } + +}
\ No newline at end of file diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/LoadUserSchemasOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/LoadUserSchemasOperation.java new file mode 100644 index 00000000000..6363aff9410 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/LoadUserSchemasOperation.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.IOseeSchemaProvider; +import org.eclipse.osee.framework.core.datastore.SchemaCreationOptions; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata; +import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement; +import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey; +import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement; +import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaXmlParser; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.core.exception.OseeExceptions; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.core.ConnectionHandler; +import org.eclipse.osee.framework.jdk.core.util.Strings; + +/** + * @author Roberto E. Escobar + */ +public class LoadUserSchemasOperation extends AbstractOperation { + + private final Map<String, SchemaData> schemas; + private final IOseeSchemaProvider schemaProvider; + private final SchemaCreationOptions options; + + public LoadUserSchemasOperation(Map<String, SchemaData> schemas, IOseeSchemaProvider schemaProvider, SchemaCreationOptions options) { + super("Load Schema Data from URIs", Activator.PLUGIN_ID); + this.schemas = schemas; + this.schemaProvider = schemaProvider; + this.options = options; + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + SchemaXmlParser parser = new SchemaXmlParser(); + parser.parseFromSchemaProvider(schemaProvider, schemas); + + if (!options.isUseFileSpecifiedSchemas()) { + try { + DatabaseMetaData meta = ConnectionHandler.getMetaData(); + if (meta != null) { + String userName = meta.getUserName(); + if (Strings.isValid(userName)) { + int index = userName.indexOf('@'); + if (index > 1) { + userName = userName.substring(0, index); + } + Map<String, SchemaData> newData = useUserNameAsSchema(userName.toUpperCase(), schemas); + schemas.clear(); + schemas.putAll(newData); + } + } + } catch (SQLException ex) { + OseeExceptions.wrapAndThrow(ex); + } + } + + if (options.isTableDataSpaceValid()) { + for (SchemaData schemaData : schemas.values()) { + schemaData.setTableDataSpaceName(options.getTableDataSpace()); + } + } + + if (options.isIndexDataSpaceValid()) { + for (SchemaData schemaData : schemas.values()) { + schemaData.setIndexDataSpaceName(options.getIndexDataSpace()); + } + } + } + + private Map<String, SchemaData> useUserNameAsSchema(String userName, Map<String, SchemaData> userSchemas) { + Map<String, SchemaData> newData = new HashMap<String, SchemaData>(); + SchemaData newSchemaData = new SchemaData(); + Set<String> keys = userSchemas.keySet(); + for (String key : keys) { + SchemaData schemaData = userSchemas.get(key); + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + TableElement newTable = useUserNameAsSchemaForTable(userName, table); + newSchemaData.addTableDefinition(newTable); + } + } + newData.put(userName, newSchemaData); + return newData; + } + + private TableElement useUserNameAsSchemaForTable(String userName, TableElement table) { + TableElement newTable = new TableElement(); + + Map<TableDescriptionFields, String> tableDescription = table.getDescription(); + Map<String, ColumnMetadata> columns = table.getColumns(); + List<ConstraintElement> constraints = table.getConstraints(); + List<ForeignKey> foreignKeys = table.getForeignKeyConstraints(); + List<IndexElement> indexElements = table.getIndexData(); + + TableDescriptionFields[] descriptors = TableDescriptionFields.values(); + for (TableDescriptionFields field : descriptors) { + String value = tableDescription.get(field); + if (field.equals(TableDescriptionFields.schema)) { + value = userName; + } + if (value != null && !value.equals("")) { + newTable.addTableDescription(field, value); + } + } + + Set<String> columnKeys = columns.keySet(); + for (String key : columnKeys) { + newTable.addColumn(columns.get(key)); + } + for (ConstraintElement constraint : constraints) { + constraint.setSchema(userName); + newTable.addConstraint(constraint); + } + for (ForeignKey constraint : foreignKeys) { + constraint.setSchema(userName); + List<ReferenceClause> references = constraint.getReferences(); + for (ReferenceClause clause : references) { + clause.setSchema(userName); + } + newTable.addConstraint(constraint); + } + for (IndexElement indexElement : indexElements) { + newTable.addIndexData(indexElement); + } + return newTable; + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/OperationFactory.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/OperationFactory.java new file mode 100644 index 00000000000..b1425572e19 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/OperationFactory.java @@ -0,0 +1,39 @@ +/*
+ * Created on Jun 21, 2010
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.core.datastore.schema.operations;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import org.eclipse.osee.framework.core.datastore.IOseeSchemaProvider;
+import org.eclipse.osee.framework.core.datastore.SchemaCreationOptions;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData;
+import org.eclipse.osee.framework.core.operation.CompositeOperation;
+import org.eclipse.osee.framework.core.operation.IOperation;
+import org.eclipse.osee.framework.database.IOseeDatabaseServiceProvider;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public final class OperationFactory {
+
+ private OperationFactory() {
+ }
+
+ public static IOperation createDbSchema(IOseeDatabaseServiceProvider provider, IOseeSchemaProvider schemaProvider, SchemaCreationOptions options) {
+ Map<String, SchemaData> userSpecifiedConfig = new HashMap<String, SchemaData>();
+ Map<String, SchemaData> currentDatabaseConfig = new HashMap<String, SchemaData>();
+
+ Collection<IOperation> ops = new ArrayList<IOperation>();
+ ops.add(new LoadUserSchemasOperation(userSpecifiedConfig, schemaProvider, options));
+ ops.add(new ExtractDatabaseSchemaOperation(provider, userSpecifiedConfig.keySet(), currentDatabaseConfig));
+ ops.add(new CreateSchemaOperation(provider, userSpecifiedConfig, currentDatabaseConfig));
+
+ return new CompositeOperation("Create OSEE Schema", Activator.PLUGIN_ID, ops);
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/PrintTables.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/PrintTables.java new file mode 100644 index 00000000000..ae2948d2d3b --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/PrintTables.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.Writer; +import java.util.Map; +import java.util.Set; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.core.ConnectionHandler; +import org.eclipse.osee.framework.database.core.IOseeStatement; + +/** + * @author Roberto E. Escobar + */ +public class PrintTables extends AbstractOperation { + + private final Map<String, SchemaData> userConfig; + private final Writer writer; + + public PrintTables(Map<String, SchemaData> userConfig, Writer writer) { + super("Print Schema", Activator.PLUGIN_ID); + this.userConfig = userConfig; + this.writer = writer; + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + Set<String> keys = userConfig.keySet(); + for (String key : keys) { + SchemaData schemaData = userConfig.get(key); + Set<String> tables = schemaData.getTableMap().keySet(); + for (String tableName : tables) { + printTable(tableName); + } + } + } + + private void printTable(String tableName) throws Exception { + IOseeStatement chStmt = ConnectionHandler.getStatement(); + try { + chStmt.runPreparedQuery("select * from " + tableName); + int numberOfColumns = chStmt.getColumnCount(); + String header = "\nTable:\t" + tableName + "\n"; + header += "Columns:\t"; + for (int index = 1; index <= numberOfColumns; index++) { + header += chStmt.getColumnName(index); + if (index + 1 <= numberOfColumns) { + header += ", "; + } + } + header += "\n"; + + writer.write(header); + + String results = ""; + while (chStmt.next()) { + results = "Data:\t"; + for (int index = 1; index <= numberOfColumns; index++) { + results += chStmt.getObject(index).toString(); + if (index + 1 <= numberOfColumns) { + results += ", "; + } + } + results += "\n"; + writer.write(results); + } + } finally { + chStmt.close(); + } + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/RestoreTableDataOperation.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/RestoreTableDataOperation.java new file mode 100644 index 00000000000..c0e1e32ddff --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/operations/RestoreTableDataOperation.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.operations; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.osee.framework.core.datastore.internal.Activator; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.datastore.schema.sql.SqlFactory; +import org.eclipse.osee.framework.core.datastore.schema.sql.SqlManager; +import org.eclipse.osee.framework.core.operation.AbstractOperation; +import org.eclipse.osee.framework.database.core.ConnectionHandler; + +/** + * @author Roberto E. Escobar + */ +public class RestoreTableDataOperation extends AbstractOperation { + private static final File backupDirectory = new File("backupDirectory"); + + private final Set<String> schemas; + private final Map<String, SchemaData> userSpecifiedConfig; + private final String importDatabaseSource; + + public RestoreTableDataOperation(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, String importDatabaseSource) { + super("Restore Table Data", Activator.PLUGIN_ID); + this.schemas = schemas; + this.userSpecifiedConfig = userSpecifiedConfig; + this.importDatabaseSource = importDatabaseSource; + } + + @Override + protected void doWork(IProgressMonitor monitor) throws Exception { + SqlManager sqlManager = SqlFactory.getSqlManager(ConnectionHandler.getMetaData()); + + for (String schemaKey : schemas) { + if (userSpecifiedConfig.containsKey(schemaKey)) { + DatabaseDataImporter importer = new DatabaseDataImporter(backupDirectory, sqlManager); + SchemaData schemaData = userSpecifiedConfig.get(schemaKey); + + setImportOrder(importer, schemaData); + setTablesToImport(importer, schemaData); + importer.setSchemaToImportTo(schemaKey); + + importer.importDataIntoDatabase(); + } + } + + clearBackupDirectory(); + } + + private void setImportOrder(DatabaseDataImporter importer, SchemaData schemaData) { + List<String> importOrder = new ArrayList<String>(); + + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + importOrder.add(table.getFullyQualifiedTableName()); + } + importer.setImportOrder(importOrder); + } + + private void setTablesToImport(DatabaseDataImporter importer, SchemaData schemaData) { + importer.clearTableFilter(); + Set<String> selectedTables = schemaData.getTablesToBackup(); + for (String tableName : selectedTables) { + importer.addToTableFilter(tableName); + } + Map<String, Set<String>> importedTables = schemaData.getTablesToImport(importDatabaseSource); + Set<String> keys = importedTables.keySet(); + for (String key : keys) { + Set<String> tables = importedTables.get(key); + for (String tableName : tables) { + importer.addToTableFilter(tableName); + } + } + } + + private void clearBackupDirectory() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + File[] fileList = backupDirectory.listFiles(); + for (File fileToDelete : fileList) { + fileToDelete.delete(); + } + backupDirectory.delete(); + } + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlDataType.java new file mode 100644 index 00000000000..2c4f83b7dea --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlDataType.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + + +/** + * @author Roberto E. Escobar + */ +public class DerbySqlDataType extends SqlDataType { + + public DerbySqlDataType() { + super(); + } + + @Override + public String getBooleanType() { + return "boolean"; + } + + @Override + public String getBitType() { + return "smallint"; + } + + @Override + public String getIntegerType() { + return "integer"; + } + + @Override + public String getDecimalType() { + return "decimal"; + } + + @Override + public String getFloatType() { + return "float"; + } + + @Override + public String getRealType() { + return "real"; + } + + @Override + public String getDoubleType() { + return getRealType(); + } + + @Override + public String getDateType() { + return "date"; + } + + @Override + public String getCharType() { + return "char"; + } + + @Override + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "bigint"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlManager.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlManager.java new file mode 100644 index 00000000000..b4a60793cad --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/DerbySqlManager.java @@ -0,0 +1,121 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.database.core.SQL3DataType;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DerbySqlManager extends SqlManagerImpl {
+
+ /**
+ * @param logger
+ * @param sqlDataType
+ */
+ public DerbySqlManager(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ @Override
+ public String constraintDataToSQL(ConstraintElement constraint, String tableID) {
+ StringBuilder toReturn = new StringBuilder();
+ String id = formatQuotedString(constraint.getId(), "\\.");
+ String type = constraint.getConstraintType().toString();
+ String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ",");
+
+ if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) {
+ toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")");
+
+ if (constraint instanceof ForeignKey) {
+ ForeignKey fk = (ForeignKey) constraint;
+ List<ReferenceClause> refs = fk.getReferences();
+
+ for (ReferenceClause ref : refs) {
+ String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\.");
+ String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ",");
+
+ String onUpdate = "";
+ if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) {
+ onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString();
+ }
+
+ String onDelete = "";
+ if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) {
+ onDelete = "ON DELETE " + ref.getOnDeleteAction().toString();
+ }
+
+ if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) {
+ toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")");
+ if (!onUpdate.equals("")) {
+ toReturn.append(" " + onUpdate);
+ }
+
+ if (!onDelete.equals("")) {
+ toReturn.append(" " + onDelete);
+ }
+
+ // Not Supported in Derby ?
+ // if (constraint.isDeferrable()) {
+ // toReturn.append(" DEFERRABLE");
+ // }
+ }
+
+ else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString());
+ }
+
+ }
+ }
+ } else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString());
+ }
+ return toReturn.toString();
+ }
+
+ @Override
+ public String columnDataToSQL(Map<ColumnFields, String> column) {
+ StringBuilder toReturn = new StringBuilder();
+
+ String columnLimits = column.get(ColumnFields.limits);
+ String defaultValue = column.get(ColumnFields.defaultValue);
+
+ SQL3DataType dataType = SQL3DataType.valueOf(column.get(ColumnFields.type));
+ columnLimits = sqlDataType.getLimit(dataType, columnLimits);
+ toReturn.append("\"");
+ toReturn.append(column.get(ColumnFields.id));
+ toReturn.append("\"");
+ toReturn.append(" ");
+ toReturn.append(sqlDataType.getType(dataType));
+
+ if (columnLimits != null && !columnLimits.equals("")) {
+ toReturn.append(" (" + columnLimits + ")");
+ }
+ if (defaultValue != null && !defaultValue.equals("")) {
+ toReturn.append(" " + defaultValue);
+ }
+ return toReturn.toString();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/FoxProDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/FoxProDataType.java new file mode 100644 index 00000000000..4889d4f2d82 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/FoxProDataType.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + +/** + * @author Roberto E. Escobar + */ +public class FoxProDataType extends SqlDataType { + + public FoxProDataType() { + super(); + } + + @Override + public String getBooleanType() { + return "number"; + } + + @Override + public String getBitType() { + return "number"; + } + + @Override + public String getIntegerType() { + return "integer"; + } + + @Override + public String getDecimalType() { + return "number"; + } + + @Override + public String getFloatType() { + return "float"; + } + + @Override + public String getDoubleType() { + return "number"; + } + + @Override + public String getRealType() { + return "real"; + } + + @Override + public String getDateType() { + return "date"; + } + + @Override + public String getCharType() { + return "char"; + } + + @Override + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "number"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "number"; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MySqlDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MySqlDataType.java new file mode 100644 index 00000000000..3b7c8399f8c --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MySqlDataType.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + + +/** + * @author Roberto E. Escobar + */ +public class MySqlDataType extends SqlDataType { + + public MySqlDataType() { + super(); + } + + @Override + public String getBooleanType() { + return "boolean"; + } + + @Override + public String getBitType() { + return "smallint"; + } + + @Override + public String getIntegerType() { + return "integer"; + } + + @Override + public String getDecimalType() { + return "decimal"; + } + + @Override + public String getFloatType() { + return "float"; + } + + @Override + public String getRealType() { + return "real"; + } + + @Override + public String getDoubleType() { + return getRealType(); + } + + @Override + public String getDateType() { + return "date"; + } + + @Override + public String getCharType() { + return "char"; + } + + @Override + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "blob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "bigint"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MysqlSqlManager.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MysqlSqlManager.java new file mode 100644 index 00000000000..6e9afb8f3fe --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/MysqlSqlManager.java @@ -0,0 +1,158 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import org.apache.commons.lang.StringUtils;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey;
+import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.database.core.ConnectionHandler;
+import org.eclipse.osee.framework.database.core.OseeConnection;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Andrew M. Finkbeiner
+ */
+public class MysqlSqlManager extends SqlManagerImpl {
+
+ /**
+ * @param sqlDataType
+ */
+ public MysqlSqlManager(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ private String handleColumnCreationSection(OseeConnection connection, Map<String, ColumnMetadata> columns) {
+ List<String> lines = new ArrayList<String>();
+ Set<String> keys = columns.keySet();
+ for (String key : keys) {
+ Map<ColumnFields, String> column = columns.get(key).getColumnFields();
+ lines.add(columnDataToSQL(column));
+ }
+ String toExecute = org.eclipse.osee.framework.jdk.core.util.Collections.toString(lines, ",\n");
+ return toExecute;
+ }
+
+ public void createTable(OseeConnection connection, TableElement tableDef) throws OseeDataStoreException {
+ String toExecute = "CREATE TABLE " + tableDef.getFullyQualifiedTableName() + " ( \n";
+ toExecute += handleColumnCreationSection(connection, tableDef.getColumns());
+ toExecute += handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName());
+ toExecute +=
+ handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), tableDef.getFullyQualifiedTableName());
+ toExecute += " \n)\n";
+ OseeLog.log(Activator.class, Level.INFO, "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(connection, toExecute);
+ }
+
+ @Override
+ public void dropTable(TableElement tableDef) throws OseeDataStoreException {
+ String toExecute = "DROP TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\.");
+ OseeLog.log(Activator.class, Level.INFO, "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute);
+ }
+
+ @Override
+ protected String formatQuotedString(String value, String splitAt) {
+ String[] array = value.split(splitAt);
+ for (int index = 0; index < array.length; index++) {
+ array[index] = array[index];
+ }
+ return StringUtils.join(array, splitAt.replaceAll("\\\\", ""));
+ }
+
+ @Override
+ public void dropIndex(TableElement tableDef) throws OseeDataStoreException {
+ List<IndexElement> tableIndices = tableDef.getIndexData();
+ String tableName = tableDef.getFullyQualifiedTableName();
+ for (IndexElement iData : tableIndices) {
+ if (iData.ignoreMySql()) {
+ continue;
+ }
+ OseeLog.log(Activator.class, Level.INFO, String.format("Dropping Index: [%s] FROM [%s]",
+ iData.getId(), tableName));
+ if (iData.getId().equals("PRIMARY")) {
+ ConnectionHandler.runPreparedUpdate("ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP PRIMARY KEY");
+ } else {
+ ConnectionHandler.runPreparedUpdate("ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP INDEX " + iData.getId());
+ }
+ }
+ }
+
+ @Override
+ public String constraintDataToSQL(ConstraintElement constraint, String tableID) {
+ StringBuilder toReturn = new StringBuilder();
+ String id = formatQuotedString(constraint.getId(), "\\.");
+ String type = constraint.getConstraintType().toString();
+ String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ",");
+
+ if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) {
+ toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")");
+
+ if (constraint instanceof ForeignKey) {
+ ForeignKey fk = (ForeignKey) constraint;
+ List<ReferenceClause> refs = fk.getReferences();
+
+ for (ReferenceClause ref : refs) {
+ String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\.");
+ String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ",");
+
+ String onUpdate = "";
+ if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) {
+ onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString();
+ }
+
+ String onDelete = "";
+ if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) {
+ onDelete = "ON DELETE " + ref.getOnDeleteAction().toString();
+ }
+
+ if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) {
+ toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")");
+ if (!onUpdate.equals("")) {
+ toReturn.append(" " + onUpdate);
+ }
+
+ if (!onDelete.equals("")) {
+ toReturn.append(" " + onDelete);
+ }
+
+ // if (constraint.isDeferrable()) {
+ // toReturn.append(" DEFERRABLE");
+ // }
+ }
+
+ else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString());
+ }
+
+ }
+ }
+ } else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString());
+ }
+ return toReturn.toString();
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlDataType.java new file mode 100644 index 00000000000..9043a1808fb --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlDataType.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + +import org.eclipse.osee.framework.database.core.SQL3DataType; + +/** + * @author Roberto E. Escobar + */ +public class OracleSqlDataType extends SqlDataType { + + public OracleSqlDataType() { + super(); + } + + @Override + public String getLimit(SQL3DataType dataType, String limit) { + if (dataType == SQL3DataType.VARCHAR && limit != null && !limit.equals("")) { + return limit + " CHAR"; + } else { + return super.getLimit(dataType, limit); + } + } + + @Override + public String getBooleanType() { + return "number"; + } + + @Override + public String getBitType() { + return "number"; + } + + @Override + public String getIntegerType() { + return "integer"; + } + + @Override + public String getDecimalType() { + return "number"; + } + + @Override + public String getFloatType() { + return "float"; + } + + @Override + public String getRealType() { + return "real"; + } + + @Override + public String getDoubleType() { + return "number"; + } + + @Override + public String getDateType() { + return "date"; + } + + @Override + public String getCharType() { + return "char"; + } + + @Override + public String getVarCharType() { + return "varchar2"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "number"; + } + + @Override + protected String getLongVarCharType() { + return "varchar2"; + } + + @Override + protected String getNumericType() { + return "number"; + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlManager.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlManager.java new file mode 100644 index 00000000000..f00c016f4eb --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/OracleSqlManager.java @@ -0,0 +1,82 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.database.core.ConnectionHandler;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class OracleSqlManager extends SqlManager {
+
+ public OracleSqlManager(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ protected String handleColumnCreationSection(Map<String, ColumnMetadata> columns) {
+ List<String> lines = new ArrayList<String>();
+ Set<String> keys = columns.keySet();
+ for (String key : keys) {
+ Map<ColumnFields, String> column = columns.get(key).getColumnFields();
+ lines.add(columnDataToSQL(column));
+ }
+ String toExecute = org.eclipse.osee.framework.jdk.core.util.Collections.toString(lines, ",\n");
+ return toExecute;
+ }
+
+ @Override
+ public void createTable(TableElement tableDef) throws OseeDataStoreException {
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append(SqlManager.CREATE_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(),
+ "\\.") + " ( \n");
+ toExecute.append(handleColumnCreationSection(tableDef.getColumns()));
+ toExecute.append(handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName()));
+ toExecute.append(handleConstraintCreationSection(tableDef.getForeignKeyConstraints(),
+ tableDef.getFullyQualifiedTableName()));
+ toExecute.append(" \n)");
+ toExecute.append(" tablespace ");
+ toExecute.append(tableDef.getTablespace());
+ toExecute.append("\n");
+ OseeLog.log(Activator.class, Level.FINE,
+ "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute.toString());
+ }
+
+ @Override
+ protected String createIndexPostProcess(IndexElement indexElement, String original) {
+ StringBuilder buffer = new StringBuilder(original);
+ buffer.append(" tablespace ");
+ buffer.append(indexElement.getTablespace());
+ return buffer.toString();
+ }
+
+ @Override
+ public void dropTable(TableElement tableDef) throws OseeDataStoreException {
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append(SqlManager.DROP_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(),
+ "\\.") + " cascade constraints purge");
+ OseeLog.log(Activator.class, Level.FINE,
+ "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute.toString());
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgreSqlManager.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgreSqlManager.java new file mode 100644 index 00000000000..9036b5cd7c2 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgreSqlManager.java @@ -0,0 +1,201 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import org.apache.commons.lang.StringUtils;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey;
+import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.database.core.ConnectionHandler;
+import org.eclipse.osee.framework.database.core.OseeConnection;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Andrew M. Finkbeiner
+ */
+public class PostgreSqlManager extends SqlManagerImpl {
+ /**
+ * @param sqlDataType
+ */
+ public PostgreSqlManager(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ private String handleColumnCreationSection(OseeConnection connection, Map<String, ColumnMetadata> columns) {
+ List<String> lines = new ArrayList<String>();
+ Set<String> keys = columns.keySet();
+ for (String key : keys) {
+ Map<ColumnFields, String> column = columns.get(key).getColumnFields();
+ lines.add(columnDataToSQL(column));
+ }
+ String toExecute = org.eclipse.osee.framework.jdk.core.util.Collections.toString(lines, ",\n");
+ return toExecute;
+ }
+
+ public void createTable(OseeConnection connection, TableElement tableDef) throws OseeDataStoreException {
+ String toExecute = "CREATE TABLE " + tableDef.getFullyQualifiedTableName() + " ( \n";
+ toExecute += handleColumnCreationSection(connection, tableDef.getColumns());
+ toExecute += handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName());
+ toExecute +=
+ handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), tableDef.getFullyQualifiedTableName());
+ toExecute += " \n)\n";
+ OseeLog.log(Activator.class, Level.FINE,
+ "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(connection, toExecute);
+ }
+
+ @Override
+ public void dropTable(TableElement tableDef) throws OseeDataStoreException {
+ String toExecute = "DROP TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\.") + " CASCADE";
+ OseeLog.log(Activator.class, Level.FINE,
+ "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute);
+ }
+
+ @Override
+ protected String formatQuotedString(String value, String splitAt) {
+ String[] array = value.split(splitAt);
+ for (int index = 0; index < array.length; index++) {
+ array[index] = array[index];
+ }
+ return StringUtils.join(array, splitAt.replaceAll("\\\\", ""));
+ }
+
+ public void dropIndex(OseeConnection connection, TableElement tableDef) throws OseeDataStoreException {
+ List<IndexElement> tableIndices = tableDef.getIndexData();
+ String tableName = tableDef.getFullyQualifiedTableName();
+ for (IndexElement iData : tableIndices) {
+ if (iData.ignoreMySql()) {
+ continue;
+ }
+ OseeLog.log(Activator.class, Level.FINE, String.format("Dropping Index: [%s] FROM [%s]\n",
+ iData.getId(), tableName));
+ if (iData.getId().equals("PRIMARY")) {
+ ConnectionHandler.runPreparedUpdate(connection,
+ "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP PRIMARY KEY");
+ } else {
+ ConnectionHandler.runPreparedUpdate(connection,
+ "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP INDEX " + iData.getId());
+ }
+ }
+ }
+
+ @Override
+ public String constraintDataToSQL(ConstraintElement constraint, String tableID) {
+ StringBuilder toReturn = new StringBuilder();
+ String id = formatQuotedString(constraint.getId(), "\\.");
+ String type = constraint.getConstraintType().toString();
+ String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ",");
+
+ if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) {
+ toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")");
+
+ if (constraint instanceof ForeignKey) {
+ ForeignKey fk = (ForeignKey) constraint;
+ List<ReferenceClause> refs = fk.getReferences();
+
+ for (ReferenceClause ref : refs) {
+ String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\.");
+ String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ",");
+
+ String onUpdate = "";
+ if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) {
+ onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString();
+ }
+
+ String onDelete = "";
+ if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) {
+ onDelete = "ON DELETE " + ref.getOnDeleteAction().toString();
+ }
+
+ if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) {
+ toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")");
+ if (!onUpdate.equals("")) {
+ toReturn.append(" " + onUpdate);
+ }
+
+ if (!onDelete.equals("")) {
+ toReturn.append(" " + onDelete);
+ }
+
+ if (constraint.isDeferrable()) {
+ toReturn.append(" DEFERRABLE");
+ }
+ }
+
+ else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString());
+ }
+
+ }
+ }
+ } else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString());
+ }
+ return toReturn.toString();
+ }
+
+ public void createIndex(OseeConnection connection, TableElement tableDef) throws OseeDataStoreException {
+ List<IndexElement> tableIndices = tableDef.getIndexData();
+ String indexId = null;
+ StringBuilder appliesTo = new StringBuilder();
+ String tableName = formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\.");
+ for (IndexElement iData : tableIndices) {
+ if (iData.ignoreMySql()) {
+ continue;
+ }
+ indexId = iData.getId();
+ appliesTo.delete(0, appliesTo.length());
+
+ List<AppliesToClause> appliesToList = iData.getAppliesToList();
+ for (int index = 0; index < appliesToList.size(); index++) {
+ AppliesToClause record = appliesToList.get(index);
+ appliesTo.append(record.getColumnName());
+
+ // switch (record.getOrderType()) {
+ // case Ascending:
+ // appliesTo.append(" ASC");
+ // break;
+ // case Descending:
+ // appliesTo.append(" DESC");
+ // break;
+ // default:
+ // break;
+ // }
+ if (index + 1 < appliesToList.size()) {
+ appliesTo.append(", ");
+ }
+ }
+ String toExecute =
+ String.format(CREATE_STRING + " " + iData.getIndexType() + " INDEX %s ON %s (%s)", indexId, tableName,
+ appliesTo);
+ OseeLog.log(Activator.class, Level.FINE, toExecute);
+ ConnectionHandler.runPreparedUpdate(connection, toExecute);
+ }
+ }
+
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgresqlDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgresqlDataType.java new file mode 100644 index 00000000000..2837d55559d --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/PostgresqlDataType.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + + +/** + * @author Roberto E. Escobar + */ +public class PostgresqlDataType extends SqlDataType { + + public PostgresqlDataType() { + super(); + } + + @Override + public String getBooleanType() { + return "bool"; + } + + @Override + public String getBitType() { + return "number"; + } + + @Override + public String getIntegerType() { + return "integer"; + } + + @Override + public String getDecimalType() { + return "decimal"; + } + + @Override + public String getFloatType() { + return "float"; + } + + @Override + public String getRealType() { + return "float8"; + } + + @Override + public String getDoubleType() { + return "numeric"; + } + + @Override + public String getDateType() { + return "date"; + } + + @Override + public String getCharType() { + return "char"; + } + + @Override + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "text"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "bytea"; + } + + @Override + protected String getBigInt() { + return "numeric"; + } + + @Override + protected String getLongVarCharType() { + return "varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SchemaSqlUtil.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SchemaSqlUtil.java new file mode 100644 index 00000000000..6c63551d795 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SchemaSqlUtil.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.core.datastore.schema.data.SchemaData; +import org.eclipse.osee.framework.core.datastore.schema.data.TableElement; +import org.eclipse.osee.framework.core.exception.OseeDataStoreException; + +public class SchemaSqlUtil { + private final SqlManager sqlManager; + + public SchemaSqlUtil(SqlManager sqlManager) { + this.sqlManager = sqlManager; + } + + public void addIndices(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (userSpecifiedConfig.containsKey(schemaId)) { + SchemaData schemaData = userSpecifiedConfig.get(schemaId); + + for (TableElement tableDef : schemaData.getTableMap().values()) { + sqlManager.createIndex(tableDef); + } + } + } + } + + public void addTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (userSpecifiedConfig.containsKey(schemaId)) { + SchemaData schemaData = userSpecifiedConfig.get(schemaId); + + List<TableElement> tableDefs = schemaData.getTablesOrderedByDependency(); + for (TableElement tableDef : tableDefs) { + sqlManager.createTable(tableDef); + } + } + } + } + + public void dropTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Map<String, SchemaData> currentDatabaseConfig) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (currentDatabaseConfig.containsKey(schemaId)) { + SchemaData currentDbSchemaData = currentDatabaseConfig.get(schemaId); + SchemaData userSchema = userSpecifiedConfig.get(schemaId); + Map<String, TableElement> currentDBmap = currentDbSchemaData.getTableMap(); + Map<String, TableElement> userDbMap = userSchema.getTableMap(); + Set<String> currentDbKeys = currentDBmap.keySet(); + Set<String> userDbKeys = userDbMap.keySet(); + + SchemaData toDrop = new SchemaData(); + for (String userKey : userDbKeys) { + if (currentDbKeys.contains(userKey)) { + toDrop.addTableDefinition(currentDBmap.get(userKey)); + } + } + + List<TableElement> tableDefs = toDrop.getTablesOrderedByDependency(); + for (int index = tableDefs.size() - 1; index >= 0; index--) { + TableElement tableDef = tableDefs.get(index); + sqlManager.dropTable(tableDef); + } + } + } + } + + public void dropIndices(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Map<String, SchemaData> currentDatabaseConfig) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (currentDatabaseConfig.containsKey(schemaId)) { + SchemaData currentDbSchemaData = currentDatabaseConfig.get(schemaId); + SchemaData userSchema = userSpecifiedConfig.get(schemaId); + Map<String, TableElement> currentDBmap = currentDbSchemaData.getTableMap(); + Map<String, TableElement> userDbMap = userSchema.getTableMap(); + Set<String> currentDbKeys = currentDBmap.keySet(); + Set<String> userDbKeys = userDbMap.keySet(); + + SchemaData toDrop = new SchemaData(); + for (String userKey : userDbKeys) { + if (currentDbKeys.contains(userKey)) { + toDrop.addTableDefinition(currentDBmap.get(userKey)); + } + } + + for (TableElement tableDef : toDrop.getTableMap().values()) { + sqlManager.dropIndex(tableDef); + } + } + } + } + + public void createSchema(Set<String> schemas) throws OseeDataStoreException { + for (String schemaId : schemas) { + sqlManager.createSchema(schemaId.toLowerCase()); + } + } + + public void dropSchema(Set<String> schemas) throws OseeDataStoreException { + for (String schemaId : schemas) { + sqlManager.dropSchema(schemaId.toLowerCase()); + } + } + +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlDataType.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlDataType.java new file mode 100644 index 00000000000..bf83c0da036 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlDataType.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.database.core.SQL3DataType; + +/** + * @author Roberto E. Escobar + */ +public abstract class SqlDataType { + + public SqlDataType() { + super(); + } + + protected abstract String getBooleanType(); + + protected abstract String getBitType(); + + protected abstract String getSmallIntType(); + + protected abstract String getIntegerType(); + + protected abstract String getDecimalType(); + + protected abstract String getFloatType(); + + protected abstract String getDoubleType(); + + protected abstract String getRealType(); + + protected abstract String getDateType(); + + protected abstract String getCharType(); + + protected abstract String getVarCharType(); + + protected abstract String getClobType(); + + protected abstract String getBlobType(); + + protected abstract String getTimestamp(); + + protected abstract String getTime(); + + protected abstract String getBigInt(); + + protected abstract String getLongVarCharType(); + + protected abstract String getNumericType(); + + public String getLimit(SQL3DataType dataType, String limit) { + return limit; + } + + public String getType(SQL3DataType dataType) { + String toReturn = ""; + + switch (dataType) { + case BOOLEAN: + toReturn = this.getBooleanType(); + break; + case BIT: + toReturn = this.getBitType(); + break; + case SMALLINT: + toReturn = this.getSmallIntType(); + break; + case INTEGER: + toReturn = this.getIntegerType(); + break; + case REAL: + toReturn = this.getRealType(); + break; + case DECIMAL: + toReturn = this.getDecimalType(); + break; + case FLOAT: + toReturn = this.getFloatType(); + break; + case DOUBLE: + toReturn = this.getDoubleType(); + break; + case DATE: + toReturn = this.getDateType(); + break; + case CHAR: + toReturn = this.getCharType(); + break; + case VARCHAR: + toReturn = this.getVarCharType(); + break; + case CLOB: + toReturn = this.getClobType(); + break; + case TIMESTAMP: + toReturn = this.getTimestamp(); + break; + case TIME: + toReturn = this.getTime(); + break; + case BLOB: + toReturn = this.getBlobType(); + break; + case BIGINT: + toReturn = this.getBigInt(); + break; + case LONGVARCHAR: + toReturn = this.getLongVarCharType(); + break; + case NUMERIC: + toReturn = this.getNumericType(); + break; + default: + toReturn = "ADDTHISTYPE:" + dataType.name(); + break; + } + return toReturn; + } + + public String formatDataValueforDataType(String columnValue, SQL3DataType columnType) { + String toReturn = ""; + switch (columnType) { + case BIGINT: + case BIT: + case BOOLEAN: + case DECIMAL: + case DOUBLE: + case FLOAT: + case INTEGER: + case REAL: + case NUMERIC: + case SMALLINT: + case TINYINT: + toReturn = ((columnValue != null && !columnValue.equals("")) ? columnValue : "0"); + break; + case DATE: + toReturn = "{d '" + formatDate(columnValue) + "'}"; + break; + case TIMESTAMP: + toReturn = "{ts '" + formatDate(columnValue) + "'}"; + break; + case TIME: + toReturn = "{t '" + columnValue + "'}"; + break; + default: + toReturn = "'" + columnValue + "'"; + break; + } + return toReturn; + } + + private String formatDate(String input) { + String[] sets = input.split(" "); + String date = sets[0]; + String time = ""; + if (sets.length > 1) { + time += " "; + for (int i = 1; i < sets.length; i++) { + time += sets[i]; + } + } + if (!date.contains("/") && !date.contains("-") && !date.contains(":")) { + Pattern pattern = Pattern.compile("([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])"); + Matcher matcher = pattern.matcher(date); + + if (matcher.find()) { + if (matcher.groupCount() == 3) { + String year = matcher.group(1); + String month = matcher.group(2); + String day = matcher.group(3); + + date = year + "-" + month + "-" + day; + } + } + } else { + date = date.replaceAll("/", "-"); + date = date.replaceAll(":", "-"); + } + return date + time; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlFactory.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlFactory.java new file mode 100644 index 00000000000..b170c473f35 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlFactory.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * 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: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.core.datastore.schema.sql; + +import java.sql.DatabaseMetaData; +import org.eclipse.osee.framework.core.exception.OseeDataStoreException; +import org.eclipse.osee.framework.database.core.SupportedDatabase; + +/** + * @author Roberto E. Escobar + */ +public class SqlFactory { + + private SqlFactory() { + super(); + } + + public static SqlManager getSqlManager(DatabaseMetaData metaData) throws OseeDataStoreException { + return getSqlManager(SupportedDatabase.getDatabaseType(metaData)); + } + + private static SqlManager getSqlManager(SupportedDatabase db) { + SqlManager instance = null; + switch (db) { + case oracle: + instance = new OracleSqlManager(new OracleSqlDataType()); + break; + case derby: + instance = new DerbySqlManager(new DerbySqlDataType()); + break; + case foxpro: + instance = new SqlManagerImpl(new FoxProDataType()); + break; + case mysql: + instance = new MysqlSqlManager(new MySqlDataType()); + break; + case postgresql: + instance = new PostgreSqlManager(new PostgresqlDataType()); + break; + default: + instance = null; + break; + } + return instance; + } +} diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManager.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManager.java new file mode 100644 index 00000000000..cc3cbb295b5 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManager.java @@ -0,0 +1,308 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import org.apache.commons.lang.StringUtils;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.AppliesToClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnDbData;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.ConstraintElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ForeignKey;
+import org.eclipse.osee.framework.core.datastore.schema.data.IndexElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause;
+import org.eclipse.osee.framework.core.datastore.schema.data.SchemaDataLookup;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnDeleteEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.ReferenceClause.OnUpdateEnum;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.database.core.ConnectionHandler;
+import org.eclipse.osee.framework.database.core.SQL3DataType;
+import org.eclipse.osee.framework.jdk.core.util.time.GlobalTime;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public abstract class SqlManager {
+ protected SqlDataType sqlDataType;
+ public static final String CREATE_STRING = "CREATE";
+ public static final String DROP_STRING = "DROP";
+
+ public SqlManager(SqlDataType sqlDataType) {
+ this.sqlDataType = sqlDataType;
+ }
+
+ public abstract void createTable(TableElement tableDef) throws OseeDataStoreException;
+
+ public abstract void dropTable(TableElement tableDef) throws OseeDataStoreException;
+
+ public void insertData(List<ColumnDbData> rowData, TableElement tableMetadata) throws OseeDataStoreException {
+ List<String> columnNames = new ArrayList<String>();
+ List<String> placeHolders = new ArrayList<String>();
+ List<String> columnValues = new ArrayList<String>();
+ List<SQL3DataType> columnTypes = new ArrayList<SQL3DataType>();
+
+ for (ColumnDbData dbData : rowData) {
+ String columnId = dbData.getColumnName();
+ String columnValue = dbData.getColumnValue();
+
+ ColumnMetadata columnMetadata = SchemaDataLookup.getColumnDefinition(tableMetadata.getColumns(), columnId);
+ SQL3DataType type = SQL3DataType.valueOf(columnMetadata.getColumnField(ColumnFields.type));
+
+ columnNames.add("\"" + columnId + "\"");
+ placeHolders.add("?");
+ columnValues.add(columnValue);
+ columnTypes.add(type);
+ }
+
+ String toExecute =
+ "INSERT INTO " + formatQuotedString(tableMetadata.getFullyQualifiedTableName(), "\\.") + " (\n";
+ toExecute += StringUtils.join(columnNames, ",");
+ toExecute += "\n) VALUES (\n";
+ toExecute += StringUtils.join(placeHolders, ",");
+ toExecute += ")\n";
+
+ Object[] data = new Object[columnNames.size()];
+ for (int index = 0; index < columnNames.size(); index++) {
+ data[index] = preparedStatementHelper(columnTypes.get(index), columnValues.get(index));
+ }
+ ConnectionHandler.runPreparedUpdate(toExecute, data);
+ }
+
+ public Object preparedStatementHelper(SQL3DataType columnType, String value) throws OseeDataStoreException {
+ switch (columnType) {
+ case BINARY:
+ case BIT:
+ return value != null && !value.equals("") ? Byte.parseByte(value) : 0;
+ case TINYINT:
+ case SMALLINT:
+ return value != null && !value.equals("") ? Short.valueOf(value) : 0;
+ case INTEGER:
+ return value != null && !value.equals("") ? Integer.valueOf(value) : 0;
+ case BIGINT:
+ return value != null && !value.equals("") ? BigDecimal.valueOf(Double.valueOf(value)) : new BigDecimal(0);
+ case FLOAT:
+ return value != null && !value.equals("") ? Float.valueOf(value) : 0.0f;
+ case NUMERIC:
+ case DECIMAL:
+ case REAL:
+ case DOUBLE:
+ return value != null && !value.equals("") ? Double.valueOf(value) : 0.0;
+ case CHAR:
+ case VARCHAR:
+ case LONGVARCHAR:
+ return value;
+ case DATE:
+ return value == null || value.equals("") ? SQL3DataType.DATE : Date.valueOf(value);
+ case TIMESTAMP:
+ return value != null && !value.equals("") ? Timestamp.valueOf(value) : GlobalTime.GreenwichMeanTimestamp();
+ case TIME:
+ return value == null || value.equals("") ? SQL3DataType.TIME : Time.valueOf(value);
+ case VARBINARY:
+ case LONGVARBINARY:
+ return value.getBytes();
+ case BLOB:
+ return new BufferedInputStream(new ByteArrayInputStream(value.getBytes()));
+ case CLOB:
+ return new BufferedInputStream(new ByteArrayInputStream(value.getBytes()));
+ case BOOLEAN:
+ return value == null || value.equals("") ? false : Boolean.parseBoolean(value);
+ default:
+ throw new OseeDataStoreException("unexpected column type: " + columnType);
+ }
+ }
+
+ public String getType(SQL3DataType dataType) {
+ return sqlDataType.getType(dataType);
+ }
+
+ public String columnDataToSQL(Map<ColumnFields, String> column) {
+ StringBuilder toReturn = new StringBuilder();
+
+ String columnLimits = column.get(ColumnFields.limits);
+ String defaultValue = column.get(ColumnFields.defaultValue);
+
+ SQL3DataType dataType = SQL3DataType.valueOf(column.get(ColumnFields.type));
+ columnLimits = sqlDataType.getLimit(dataType, columnLimits);
+ toReturn.append(column.get(ColumnFields.id));
+ toReturn.append(" ");
+ toReturn.append(sqlDataType.getType(dataType));
+
+ if (columnLimits != null && !columnLimits.equals("")) {
+ toReturn.append(" (" + columnLimits + ")");
+ }
+ if (defaultValue != null && !defaultValue.equals("")) {
+ toReturn.append(" " + defaultValue);
+ }
+ return toReturn.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ protected String handleConstraintCreationSection(List constraints, String tableId) {
+ List<String> constraintStatements = new ArrayList<String>();
+ for (Object object : constraints) {
+ ConstraintElement constraint = (ConstraintElement) object;
+ constraintStatements.add(constraintDataToSQL(constraint, tableId));
+ }
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append((constraintStatements.size() != 0 ? ",\n" : ""));
+ toExecute.append(StringUtils.join(constraintStatements, ",\n"));
+ return toExecute.toString();
+ }
+
+ protected String formatQuotedString(String value, String splitAt) {
+ String[] array = value.split(splitAt);
+ for (int index = 0; index < array.length; index++) {
+ array[index] = "\"" + array[index] + "\"";
+ }
+ return StringUtils.join(array, splitAt.replaceAll("\\\\", ""));
+ }
+
+ public String constraintDataToSQL(ConstraintElement constraint, String tableID) {
+ StringBuilder toReturn = new StringBuilder();
+ String id = formatQuotedString(constraint.getId(), "\\.");
+ String type = constraint.getConstraintType().toString();
+ String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ",");
+
+ if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) {
+ toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")");
+
+ if (constraint instanceof ForeignKey) {
+ ForeignKey fk = (ForeignKey) constraint;
+ List<ReferenceClause> refs = fk.getReferences();
+
+ for (ReferenceClause ref : refs) {
+ String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\.");
+ String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ",");
+
+ String onUpdate = "";
+ if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) {
+ onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString();
+ }
+
+ String onDelete = "";
+ if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) {
+ onDelete = "ON DELETE " + ref.getOnDeleteAction().toString();
+ }
+
+ if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) {
+ toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")");
+ if (!onUpdate.equals("")) {
+ toReturn.append(" " + onUpdate);
+ }
+
+ if (!onDelete.equals("")) {
+ toReturn.append(" " + onDelete);
+ }
+
+ if (constraint.isDeferrable()) {
+ toReturn.append(" DEFERRABLE");
+ }
+ }
+
+ else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString());
+ }
+
+ }
+ }
+ } else {
+ OseeLog.log(Activator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString());
+ }
+ return toReturn.toString();
+ }
+
+ public void createSchema(String schema) throws OseeDataStoreException {
+ ConnectionHandler.runPreparedUpdate(CREATE_STRING + " SCHEMA \"" + schema + "\"");
+ }
+
+ public void dropSchema(String schema) throws OseeDataStoreException {
+ ConnectionHandler.runPreparedUpdate(DROP_STRING + " SCHEMA \"" + schema + "\" CASCADE");
+ }
+
+ protected String insertDataToSQL(String fullyQualifiedTableName, List<String> columns, List<String> columnData) {
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append("INSERT INTO " + formatQuotedString(fullyQualifiedTableName, "\\.") + " (\n");
+ toExecute.append(StringUtils.join(columns, ","));
+ toExecute.append("\n) VALUES (\n");
+ toExecute.append(StringUtils.join(columnData, ","));
+ toExecute.append(")\n");
+ return toExecute.toString();
+ }
+
+ public void createIndex(TableElement tableDef) throws OseeDataStoreException {
+ List<IndexElement> tableIndices = tableDef.getIndexData();
+ String indexId = null;
+ StringBuilder appliesTo = new StringBuilder();
+ String tableName = formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\.");
+ for (IndexElement iData : tableIndices) {
+ if (iData.ignoreMySql()) {
+ continue;
+ }
+ indexId = iData.getId();
+ appliesTo.delete(0, appliesTo.length());
+
+ List<AppliesToClause> appliesToList = iData.getAppliesToList();
+ for (int index = 0; index < appliesToList.size(); index++) {
+ AppliesToClause record = appliesToList.get(index);
+ appliesTo.append(record.getColumnName());
+
+ switch (record.getOrderType()) {
+ case Ascending:
+ appliesTo.append(" ASC");
+ break;
+ case Descending:
+ appliesTo.append(" DESC");
+ break;
+ default:
+ break;
+ }
+ if (index + 1 < appliesToList.size()) {
+ appliesTo.append(", ");
+ }
+ }
+ String toExecute =
+ String.format("%s %s INDEX %s ON %s (%s)", CREATE_STRING, iData.getIndexType(), indexId, tableName,
+ appliesTo);
+ toExecute = createIndexPostProcess(iData, toExecute);
+ OseeLog.log(Activator.class, Level.FINE, toExecute);
+ ConnectionHandler.runPreparedUpdate(toExecute);
+ }
+ }
+
+ protected String createIndexPostProcess(IndexElement indexElement, String original) {
+ return original;
+ }
+
+ public void dropIndex(TableElement tableDef) throws OseeDataStoreException {
+ List<IndexElement> tableIndices = tableDef.getIndexData();
+ String tableName = tableDef.getFullyQualifiedTableName();
+ for (IndexElement iData : tableIndices) {
+ OseeLog.log(Activator.class, Level.FINE, String.format("Dropping Index: [%s] FROM [%s]\n",
+ iData.getId(), tableName));
+ ConnectionHandler.runPreparedUpdate(DROP_STRING + " INDEX " + iData.getId());
+ }
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManagerImpl.java b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManagerImpl.java new file mode 100644 index 00000000000..3c06692ceb8 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/src/org/eclipse/osee/framework/core/datastore/schema/sql/SqlManagerImpl.java @@ -0,0 +1,68 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * 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:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.core.datastore.schema.sql;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.core.datastore.internal.Activator;
+import org.eclipse.osee.framework.core.datastore.schema.data.ColumnMetadata;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement;
+import org.eclipse.osee.framework.core.datastore.schema.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.core.exception.OseeDataStoreException;
+import org.eclipse.osee.framework.database.core.ConnectionHandler;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class SqlManagerImpl extends SqlManager {
+
+ public SqlManagerImpl(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ private String handleColumnCreationSection(Map<String, ColumnMetadata> columns) {
+ List<String> lines = new ArrayList<String>();
+ Set<String> keys = columns.keySet();
+ for (String key : keys) {
+ Map<ColumnFields, String> column = columns.get(key).getColumnFields();
+ lines.add(columnDataToSQL(column));
+ }
+ String toExecute = org.eclipse.osee.framework.jdk.core.util.Collections.toString(lines, ",\n");
+ return toExecute;
+ }
+
+ @Override
+ public void createTable(TableElement tableDef) throws OseeDataStoreException {
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append(SqlManager.CREATE_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(),
+ "\\.") + " ( \n");
+ toExecute.append(handleColumnCreationSection(tableDef.getColumns()));
+ toExecute.append(handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName()));
+ toExecute.append(handleConstraintCreationSection(tableDef.getForeignKeyConstraints(),
+ tableDef.getFullyQualifiedTableName()));
+ toExecute.append(" \n)\n");
+ OseeLog.log(Activator.class, Level.FINE, "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute.toString());
+ }
+
+ @Override
+ public void dropTable(TableElement tableDef) throws OseeDataStoreException {
+ StringBuilder toExecute = new StringBuilder();
+ toExecute.append(SqlManager.DROP_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(),
+ "\\."));
+ OseeLog.log(Activator.class, Level.FINE, "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]");
+ ConnectionHandler.runPreparedUpdate(toExecute.toString());
+ }
+}
diff --git a/plugins/org.eclipse.osee.framework.core.datastore/support/SKYNET.VERSIONING.SCHEMA.xml b/plugins/org.eclipse.osee.framework.core.datastore/support/SKYNET.VERSIONING.SCHEMA.xml new file mode 100644 index 00000000000..8d85fc24694 --- /dev/null +++ b/plugins/org.eclipse.osee.framework.core.datastore/support/SKYNET.VERSIONING.SCHEMA.xml @@ -0,0 +1,620 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<TableConfig>
+
+ <!-- _____________________________________________________ -->
+ <!-- -->
+ <!-- MAIN ARTIFACT TABLES -->
+ <!-- -->
+ <!-- _____________________________________________________ -->
+
+ <Table name="OSEE_ARTIFACT" schema="OSEE" tablespace="osee_data">
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="GUID" defaultValue="not null" limits="22" type="VARCHAR" />
+ <Column id="HUMAN_READABLE_ID" defaultValue="not null" limits="5" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ARTS__G_A_PK" type="PRIMARY KEY" appliesTo="ART_ID, GAMMA_ID" />
+ <Constraint schema="OSEE" id="OSEE_ARTS__ART_TYPE_ID_FK" type="FOREIGN KEY" appliesTo="ART_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ARTIFACT_TYPE" column="ART_TYPE_ID" />
+ </Constraint>
+ <Index id="OSEE_ARTS__ART_ID_IDX" tablespace="osee_index">
+ <AppliesTo id="ART_ID"/>
+ </Index>
+ <Index id="OSEE_ARTS__GUID_IDX" tablespace="osee_index">
+ <AppliesTo id="GUID"/>
+ </Index>
+ <Index id="OSEE_ARTS__ART_TYPE_ID_IDX" tablespace="osee_index">
+ <AppliesTo id="ART_TYPE_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_JOIN_ARTIFACT" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="TRANSACTION_ID" type="INTEGER" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Index id="OSEE_JOIN_ART__Q_A_B_T_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ <AppliesTo id="ART_ID"/>
+ <AppliesTo id="BRANCH_ID"/>
+ <AppliesTo id="TRANSACTION_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_JOIN_ID" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ID" type="INTEGER" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Index id="OSEE_JOIN_ID__Q_I_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ <AppliesTo id="ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_JOIN_CLEANUP" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="SESSION_ID" defaultValue="not null" type="VARCHAR" limits="28" />
+ <Column id="TABLE_NAME" defaultValue="not null" type="VARCHAR" limits="28"/>
+ <Index id="OSEE_JOIN_CLEANUP__Q_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_JOIN_CHAR_ID" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ID" defaultValue="not null" type="VARCHAR" limits="4000"/>
+ <Index id="OSEE_JOIN_CHAR__Q_IDX" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_ARTIFACT_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="ART_TYPE_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="IS_ABSTRACT" defaultValue="not null" type="smallint" />
+ <Column id="NAME" defaultValue="not null" limits="75" type="VARCHAR" />
+ <Column id="IMAGE" type="BLOB" />
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_AR_PK" type="PRIMARY KEY" appliesTo="ART_TYPE_ID" />
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_G_IDX" type="UNIQUE" appliesTo="ART_TYPE_GUID" />
+ <Index id="OSEE_ARTIFACT_TYPE_N_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="NAME"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_ARTIFACT_TYPE_INHERITANCE" schema="OSEE" tablespace="osee_data">
+ <Column id="ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="SUPER_ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Constraint schema="OSEE" id="OSEE_ART_TYPE_INHERIT_PK" type="PRIMARY KEY" appliesTo="ART_TYPE_ID, SUPER_ART_TYPE_ID" />
+ <Constraint schema="OSEE" id="OSEE_ART_TYPE_ITEM_FK" type="FOREIGN KEY" appliesTo="ART_TYPE_ID">
+ <References schema="OSEE" table="OSEE_ARTIFACT_TYPE" column="ART_TYPE_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_ART_SUPER_TYPE_FK" type="FOREIGN KEY" appliesTo="SUPER_ART_TYPE_ID">
+ <References schema="OSEE" table="OSEE_ARTIFACT_TYPE" column="ART_TYPE_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_ARTIFACT_TYPE_ATTRIBUTES" schema="OSEE" tablespace="osee_data">
+ <Column id="ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ATTR_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="BRANCH_ID" type="INTEGER" defaultValue="not null" />
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_ATTRIB_PK" type="PRIMARY KEY" appliesTo="ART_TYPE_ID, ATTR_TYPE_ID, BRANCH_ID" />
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_ATTRIB_FK1" type="FOREIGN KEY" appliesTo="ATTR_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ATTRIBUTE_TYPE" column="ATTR_TYPE_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_ATTRIB_FK2" type="FOREIGN KEY" appliesTo="ART_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ARTIFACT_TYPE" column="ART_TYPE_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_TYPE_ATTRIB_FK3" type="FOREIGN KEY" appliesTo="BRANCH_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_ATTRIBUTE" schema="OSEE" tablespace="osee_data">
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ATTR_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ATTR_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="VALUE" limits="4000" type="VARCHAR" />
+ <Column id="URI" limits="200" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ATTRIBUTE_AT_G_PK" type="PRIMARY KEY" appliesTo="ATTR_ID, GAMMA_ID" />
+ <Index id="OSEE_ATTRIBUTE_ATT_IDX" tablespace="osee_index">
+ <AppliesTo id="ATTR_TYPE_ID"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_V_IDX" mySqlIgnore="true" tablespace="osee_index">
+ <AppliesTo id="VALUE"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_AR_V_IDX" mySqlIgnore="true" tablespace="osee_index">
+ <AppliesTo id="ART_ID"/>
+ <AppliesTo id="VALUE"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_AR_G_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="ART_ID"/>
+ <AppliesTo id="GAMMA_ID"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_G_AT_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="GAMMA_ID"/>
+ <AppliesTo id="ATTR_ID"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_G_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="GAMMA_ID"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_AT_IDX" tablespace="osee_index">
+ <AppliesTo id="ATTR_ID"/>
+ </Index>
+ <Index id="OSEE_ATTRIBUTE_AR_IDX" mySqlIgnore="true" tablespace="osee_index">
+ <AppliesTo id="ART_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_ENUM_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="ENUM_TYPE_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="ENUM_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ENUM_TYPE_NAME" defaultValue="not null" limits="500" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ENUM_TYPE_PK" type="PRIMARY KEY" appliesTo="ENUM_TYPE_ID" />
+ <Constraint schema="OSEE" id="OSEE_ENUM_TYPE_G_IDX" type="UNIQUE" appliesTo="ENUM_TYPE_GUID" />
+ </Table>
+
+ <Table name="OSEE_ENUM_TYPE_DEF" schema="OSEE" tablespace="osee_data">
+ <Column id="ENUM_ENTRY_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="ENUM_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="NAME" defaultValue="not null" limits="500" type="VARCHAR" />
+ <Column id="ORDINAL" defaultValue="not null" type="smallint" />
+ <Constraint schema="OSEE" id="OSEE_ENUM_TYPE_DEF_EO_PK" type="PRIMARY KEY" appliesTo="ENUM_TYPE_ID, ORDINAL" />
+ <Constraint schema="OSEE" id="OSEE_ENUM_TYPE_DEF_G_IDX" type="UNIQUE" appliesTo="ENUM_ENTRY_GUID" />
+ <Constraint schema="OSEE" id="ENUM_TYPE_ID_FK1" type="FOREIGN KEY" appliesTo="ENUM_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ENUM_TYPE" column="ENUM_TYPE_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_ATTRIBUTE_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="ATTR_TYPE_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="ATTR_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ATTR_BASE_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ATTR_PROVIDER_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="FILE_TYPE_EXTENSION" limits="20" type="VARCHAR" />
+ <Column id="NAME" defaultValue="not null" limits="500" type="VARCHAR" />
+ <Column id="DEFAULT_VALUE" limits="2000" type="VARCHAR" />
+ <Column id="ENUM_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="MIN_OCCURENCE" defaultValue="not null" type="INTEGER" />
+ <Column id="MAX_OCCURENCE" defaultValue="not null" type="INTEGER" />
+ <Column id="TIP_TEXT" limits="4000" type="VARCHAR" />
+ <Column id="TAGGER_ID" limits="500" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ATTRIBUTE_TYPE_AT_PK" type="PRIMARY KEY" appliesTo="ATTR_TYPE_ID" />
+ <Constraint schema="OSEE" id="OSEE_ATTRIBUTE_TYPE_G_IDX" type="UNIQUE" appliesTo="ATTR_TYPE_GUID" />
+ <Constraint schema="OSEE" id="ATTR_BASE_TYPE_ID_FK" type="FOREIGN KEY" appliesTo="ATTR_BASE_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ATTRIBUTE_BASE_TYPE" column="ATTR_BASE_TYPE_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="ATTR_PROVIDER_TYPE_ID_FK" type="FOREIGN KEY" appliesTo="ATTR_PROVIDER_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_ATTRIBUTE_PROVIDER_TYPE" column="ATTR_PROVIDER_TYPE_ID" />
+ </Constraint>
+ <Index id="OSEE_ATTRIBUTE_TYPE_N_IDX" tablespace="osee_index">
+ <AppliesTo id="NAME"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_ATTRIBUTE_BASE_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="ATTR_BASE_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ATTRIBUTE_CLASS" defaultValue="not null" limits="500" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ATTR_BASE_TYPE_AT_PK" type="PRIMARY KEY" appliesTo="ATTR_BASE_TYPE_ID" />
+ </Table>
+
+ <Table name="OSEE_ATTRIBUTE_PROVIDER_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="ATTR_PROVIDER_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="ATTRIBUTE_PROVIDER_CLASS" defaultValue="not null" limits="500" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_ATTR_PROVIDER_TYPE_AT_PK" type="PRIMARY KEY" appliesTo="ATTR_PROVIDER_TYPE_ID" />
+ </Table>
+
+ <Table name="OSEE_RELATION_LINK" schema="OSEE" tablespace="osee_data">
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="REL_LINK_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="REL_LINK_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="A_ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="B_ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="RATIONALE" limits="4000" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_RELATION__G_PK" type="PRIMARY KEY" appliesTo="GAMMA_ID" />
+ <Constraint schema="OSEE" id="OSEE_RELATION__REL_TYPE_FK" type="FOREIGN KEY" appliesTo="REL_LINK_TYPE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_RELATION_LINK_TYPE" column="REL_LINK_TYPE_ID" />
+ </Constraint>
+ <Index id="OSEE_RELATION__R_G_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="REL_LINK_ID"/>
+ <AppliesTo id="GAMMA_ID"/>
+ </Index>
+ <Index id="OSEE_RELATION__A_IDX" tablespace="osee_index">
+ <AppliesTo id="A_ART_ID"/>
+ </Index>
+ <Index id="OSEE_RELATION__B_IDX" tablespace="osee_index">
+ <AppliesTo id="B_ART_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_RELATION_LINK_TYPE" schema="OSEE" tablespace="osee_data">
+ <Column id="REL_LINK_TYPE_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="REL_LINK_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="TYPE_NAME" defaultValue="not null" limits="50" type="VARCHAR" />
+ <Column id="A_NAME" defaultValue="not null" limits="50" type="VARCHAR" />
+ <Column id="B_NAME" defaultValue="not null" limits="50" type="VARCHAR" />
+ <Column id="A_ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="B_ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="MULTIPLICITY" defaultValue="not null" type="smallint" />
+ <Column id="DEFAULT_ORDER_TYPE_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Constraint schema="OSEE" id="OSEE_REL_LINK_TYPE_RLT_PK" type="PRIMARY KEY" appliesTo="REL_LINK_TYPE_ID" />
+ <Constraint schema="OSEE" id="OSEE_REL_LINK_TYPE_G_IDX" type="UNIQUE" appliesTo="REL_LINK_TYPE_GUID" />
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- MAIN VERSIONING TABLES - CHANGE, TX, AND BRANCH SUPPORT -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+
+ <Table name="OSEE_BRANCH" schema="OSEE" tablespace="osee_data">
+ <Column id="BRANCH_GUID" defaultValue="not null" limits="28" type="VARCHAR" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_NAME" defaultValue="not null" limits="200" type="VARCHAR" />
+ <Column id="PARENT_BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PARENT_TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ARCHIVED" defaultValue="not null" type="smallint" />
+ <Column id="BRANCH_STATE" defaultValue="not null" type="smallint" />
+ <Column id="ASSOCIATED_ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="BASELINE_TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+
+ <Constraint schema="OSEE" id="OSEE_BRANCH_B_PK" type="PRIMARY KEY" appliesTo="BRANCH_ID" />
+ <Constraint schema="OSEE" id="OSEE_BRANCH_G_IDX" type="UNIQUE" appliesTo="BRANCH_GUID" />
+ <!--
+ <Constraint schema="OSEE" id="OSEE_TRANSACTION_ID_FK2" type="FOREIGN KEY" appliesTo="PARENT_TRANSACTION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_TX_DETAILS" column="TRANSACTION_ID"" />
+ </Constraint>
+ -->
+ <Index id="OSEE_BRANCH_A_IDX" tablespace="osee_index">
+ <AppliesTo id="ARCHIVED" />
+ </Index>
+ </Table>
+
+ <Table name="OSEE_TXS" schema="OSEE" tablespace="osee_data">
+ <Column id="BRANCH_ID" type="INTEGER" defaultValue="not null" />
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="TX_CURRENT" defaultValue="not null" type="smallint" />
+ <Column id="MOD_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_TXS__TRANSACTION_FK" type="FOREIGN KEY" appliesTo="TRANSACTION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_TX_DETAILS" column="TRANSACTION_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_TXS__BRANCH_FK" type="FOREIGN KEY" appliesTo="BRANCH_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ <Index id="OSEE_TXS_B_G_C_M_T_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="BRANCH_ID"/>
+ <AppliesTo id="GAMMA_ID"/>
+ <AppliesTo id="TX_CURRENT"/>
+ <AppliesTo id="MOD_TYPE"/>
+ <AppliesTo id="TRANSACTION_ID" />
+ </Index>
+ </Table>
+
+ <Table name="OSEE_TXS_ARCHIVED" schema="OSEE" tablespace="osee_secondary">
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="TX_CURRENT" defaultValue="not null" type="smallint" />
+ <Column id="MOD_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_TXSA__TRANSACTION_FK" type="FOREIGN KEY" appliesTo="TRANSACTION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_TX_DETAILS" column="TRANSACTION_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_TXSA__BRANCH_FK" type="FOREIGN KEY" appliesTo="BRANCH_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ <Index id="OSEE_TXSA_B_G_C_M_T_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="BRANCH_ID"/>
+ <AppliesTo id="GAMMA_ID"/>
+ <AppliesTo id="TX_CURRENT"/>
+ <AppliesTo id="MOD_TYPE"/>
+ <AppliesTo id="TRANSACTION_ID" />
+ </Index>
+ </Table>
+
+ <Table name="OSEE_TX_DETAILS" schema="OSEE" tablespace="osee_data">
+ <Column id="TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="TX_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="OSEE_COMMENT" limits="1000" type="VARCHAR" />
+ <Column id="TIME" defaultValue="not null" type="TIMESTAMP"/>
+ <Column id="AUTHOR" defaultValue="not null" type="INTEGER"/>
+ <Column id="COMMIT_ART_ID" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_TX_DETAILS_TX_PK" type="PRIMARY KEY" appliesTo="TRANSACTION_ID" />
+ <Constraint schema="OSEE" id="BRANCH_ID_FK1" type="FOREIGN KEY" appliesTo="BRANCH_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ <Index id="OSEE_TX_DETAILS_B_TX_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="BRANCH_ID"/>
+ <AppliesTo id="TRANSACTION_ID" />
+ </Index>
+ <Index id="OSEE_TX_DETAILS_TX_B_IDX" type="UNIQUE" tablespace="osee_index">
+ <AppliesTo id="TRANSACTION_ID" />
+ <AppliesTo id="BRANCH_ID"/>
+ </Index>
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- ACCESS CONTROL LIST TABLES -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_ARTIFACT_ACL" schema="OSEE" tablespace="osee_data">
+ <Column id="ART_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PRIVILEGE_ENTITY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_ARTIFACT_ACL_A_P_B_PK" type="PRIMARY KEY" appliesTo="ART_ID, PRIVILEGE_ENTITY_ID, BRANCH_ID" />
+ <Constraint schema="OSEE" id="ARTIFACT_ACL_PERM_FK" type="FOREIGN KEY" appliesTo="PERMISSION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_PERMISSION" column="PERMISSION_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_RELATION_LINK_TYPE_ACL" schema="OSEE" tablespace="osee_data">
+ <Column id="REL_LINK_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PRIVILEGE_ENTITY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="RELATION_LINK_TYPE_ACL_PK" type="PRIMARY KEY" appliesTo="REL_LINK_TYPE_ID, PRIVILEGE_ENTITY_ID, BRANCH_ID" />
+ <Constraint schema="OSEE" id="RELATION_LINK_TYPE_PERM_FK" type="FOREIGN KEY" appliesTo="PERMISSION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_PERMISSION" column="PERMISSION_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_ARTIFACT_TYPE_ACL" schema="OSEE" tablespace="osee_data">
+ <Column id="ART_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PRIVILEGE_ENTITY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_ART_TYPE_ACL_AT_P_B_PK" type="PRIMARY KEY" appliesTo="ART_TYPE_ID, PRIVILEGE_ENTITY_ID, BRANCH_ID" />
+ <Constraint schema="OSEE" id="ARTIFACT_TYPE_PERM_FK" type="FOREIGN KEY" appliesTo="PERMISSION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_PERMISSION" column="PERMISSION_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_ATTRIBUTE_TYPE_ACL" schema="OSEE" tablespace="osee_data">
+ <Column id="ATTR_TYPE_ID" defaultValue="not null" type="smallint" />
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PRIVILEGE_ENTITY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_ATTR_TYPE_ACL_A_P_B_PK" type="PRIMARY KEY" appliesTo="ATTR_TYPE_ID, PRIVILEGE_ENTITY_ID, BRANCH_ID" />
+ <Constraint schema="OSEE" id="ATTRIBUTE_TYPE_PERM_FK" type="FOREIGN KEY" appliesTo="PERMISSION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_PERMISSION" column="PERMISSION_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_BRANCH_ACL" schema="OSEE" tablespace="osee_data">
+ <Column id="BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PRIVILEGE_ENTITY_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_BRANCH_ACL_B_P_PK" type="PRIMARY KEY" appliesTo="BRANCH_ID, PRIVILEGE_ENTITY_ID" />
+ <Constraint schema="OSEE" id="BRANCH_ACL_FK" type="FOREIGN KEY" appliesTo="BRANCH_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="BRANCH_ACL_PERM_FK" type="FOREIGN KEY" appliesTo="PERMISSION_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_PERMISSION" column="PERMISSION_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_PERMISSION" schema="OSEE" tablespace="osee_data">
+ <Column id="PERMISSION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="PERMISSION_NAME" defaultValue="not null" limits="50" type="VARCHAR" />
+ <Constraint schema="OSEE" id="PERMISSION_PK" type="PRIMARY KEY" appliesTo="PERMISSION_ID" />
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- TAGGING TABLES -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_SEARCH_TAGS" schema="OSEE" tablespace="osee_data">
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="CODED_TAG_ID" defaultValue="not null" type="BIGINT" />
+ <Constraint schema="OSEE" id="OSEE_SEARCH_TAGS__PK" type="PRIMARY KEY" appliesTo="CODED_TAG_ID, GAMMA_ID" />
+ <Index id="OSEE_SEARCH_TAGS_C_IDX" tablespace="osee_index">
+ <AppliesTo id="CODED_TAG_ID"/>
+ </Index>
+ <Index id="OSEE_SEARCH_TAGS_G_IDX" tablespace="osee_index">
+ <AppliesTo id="GAMMA_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_JOIN_SEARCH_TAGS" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="CODED_TAG_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Constraint schema="OSEE" id="OSEE_JOIN_SEARCH_TAGS_Q_C_PK" type="PRIMARY KEY" appliesTo="QUERY_ID, CODED_TAG_ID" />
+ <Index id="OSEE_JOIN_SEARCH_TAGS_Q_IDX" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ </Index>
+ </Table>
+
+ <Table name="OSEE_TAG_GAMMA_QUEUE" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Constraint schema="OSEE" id="OSEE_JOIN_GAMMA_Q_G_PK" type="PRIMARY KEY" appliesTo="QUERY_ID, GAMMA_ID" />
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- OSEE SEQUENCES and INFO -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_SEQUENCE" schema="OSEE" tablespace="osee_data">
+ <Column id="LAST_SEQUENCE" defaultValue="not null" type="BIGINT" />
+ <Column id="SEQUENCE_NAME" defaultValue="not null" type="VARCHAR" limits="128" />
+ <Constraint schema="OSEE" id="SEQUENCE_ID_UN" type="UNIQUE" appliesTo="SEQUENCE_NAME" />
+ </Table>
+
+
+ <Table name="OSEE_INFO" schema="OSEE" tablespace="osee_data">
+ <Column defaultValue="not null" id="OSEE_VALUE" type="VARCHAR" limits="1000" />
+ <Column defaultValue="not null" id="OSEE_KEY" type="VARCHAR" limits="50" />
+ <Constraint schema="OSEE" id="OSEE_INFO_KEY_UN_IDX" type="UNIQUE" appliesTo="OSEE_KEY" />
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- OSEE Merge -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_MERGE" schema="OSEE" tablespace="osee_data">
+ <Column id="SOURCE_BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="DEST_BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="MERGE_BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="COMMIT_TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_MERGE__PK" type="PRIMARY KEY" appliesTo="MERGE_BRANCH_ID" />
+ <Constraint schema="OSEE" id="OSEE_MERGE__MBI_FK" type="FOREIGN KEY" appliesTo="MERGE_BRANCH_ID">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ <Constraint schema="OSEE" id="OSEE_MERGE__DBI_FK" type="FOREIGN KEY" appliesTo="DEST_BRANCH_ID">
+ <References schema="OSEE" table="OSEE_BRANCH" column="BRANCH_ID" />
+ </Constraint>
+ </Table>
+
+ <Table name="OSEE_CONFLICT" schema="OSEE" tablespace="osee_data">
+ <Column id="CONFLICT_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="MERGE_BRANCH_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="CONFLICT_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="SOURCE_GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="DEST_GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="STATUS" defaultValue="not null" type="smallint" />
+ <Constraint schema="OSEE" id="OSEE_CONFLICT__PK" type="PRIMARY KEY" appliesTo="MERGE_BRANCH_ID, SOURCE_GAMMA_ID" />
+ <Constraint schema="OSEE" id="OSEE_CONFLICT__MBI_FK" type="FOREIGN KEY" appliesTo="MERGE_BRANCH_ID">
+ <References schema="OSEE" table="OSEE_MERGE" column="MERGE_BRANCH_ID" />
+ </Constraint>
+ </Table>
+
+
+ <Table name="OSEE_JOIN_TRANSACTION" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Index id="OSEE_JOIN_TRANSACTION_Q_IDX" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ </Index>
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- Reverted TXS -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_REMOVED_TXS" schema="OSEE" tablespace="osee_data">
+ <Column id="TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="REM_GAMMA_ID" defaultValue="not null" type="BIGINT" />
+ <Column id="REM_MOD_TYPE" defaultValue="not null" type="smallint" />
+ <Column id="REM_TX_CURRENT" defaultValue="not null" type="smallint" />
+ <Column id="REM_TRANSACTION_ID" defaultValue="not null" type="INTEGER" />
+ <Constraint schema="OSEE" id="OSEE_REM_TXS_RG_RTX_PK" type="PRIMARY KEY" appliesTo="REM_GAMMA_ID, REM_TRANSACTION_ID"/>
+ </Table>
+
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- IMPORT TABLES -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_JOIN_EXPORT_IMPORT" schema="OSEE" tablespace="osee_data">
+ <Column id="QUERY_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ID1" defaultValue="not null" type="BIGINT" />
+ <Column id="ID2" defaultValue="not null" type="BIGINT" />
+ <Column id="INSERT_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Index id="OSEE_JOIN_EXPORT_IMPORT_Q_IDX" tablespace="osee_index">
+ <AppliesTo id="QUERY_ID"/>
+ </Index>
+ </Table>
+ <Table name="OSEE_IMPORT_SOURCE" schema="OSEE" tablespace="osee_data">
+ <Column id="IMPORT_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="DB_SOURCE_GUID" defaultValue="not null" type="VARCHAR" limits="28"/>
+ <Column id="SOURCE_EXPORT_DATE" defaultValue="not null" type="TIMESTAMP" />
+ <Column id="DATE_IMPORTED" defaultValue="not null" type="TIMESTAMP" />
+ <Constraint schema="OSEE" id="OSEE_IMPORT_MAP_PK" type="PRIMARY KEY" appliesTo="IMPORT_ID" />
+ </Table>
+ <Table name="OSEE_IMPORT_SAVE_POINT" schema="OSEE" tablespace="osee_data">
+ <Column id="IMPORT_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="SAVE_POINT_NAME" defaultValue="not null" type="VARCHAR" limits="128"/>
+ <Column id="STATUS" defaultValue="not null" type="INTEGER" />
+ <Column id="STATE_ERROR" type="VARCHAR" limits="4000" />
+ <Constraint schema="OSEE" id="OSEE_IMP_SAVE_POINT_II_PK" type="PRIMARY KEY" appliesTo="IMPORT_ID, SAVE_POINT_NAME" />
+ <Constraint schema="OSEE" id="OSEE_IMP_SAVE_POINT_II_FK" type="FOREIGN KEY" appliesTo="IMPORT_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_IMPORT_SOURCE" column="IMPORT_ID" />
+ </Constraint>
+ </Table>
+ <Table name="OSEE_IMPORT_MAP" schema="OSEE" tablespace="osee_data">
+ <Column id="IMPORT_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="SEQUENCE_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="SEQUENCE_NAME" defaultValue="not null" type="VARCHAR" limits="128"/>
+ <Constraint schema="OSEE" id="OSEE_IMPORT_MAP_II_PK" type="PRIMARY KEY" appliesTo="SEQUENCE_ID" />
+ <Constraint schema="OSEE" id="OSEE_IMPORT_MAP_II_FK" type="FOREIGN KEY" appliesTo="IMPORT_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_IMPORT_SOURCE" column="IMPORT_ID" />
+ </Constraint>
+ </Table>
+ <Table name="OSEE_IMPORT_INDEX_MAP" schema="OSEE" tablespace="osee_data">
+ <Column id="SEQUENCE_ID" defaultValue="not null" type="INTEGER" />
+ <Column id="ORIGINAL_ID" defaultValue="not null" type="BIGINT"/>
+ <Column id="MAPPED_ID" defaultValue="not null" type="BIGINT" />
+ <Constraint schema="OSEE" id="OSEE_IMPORT_INDEX_MAP_IOM_PK" type="PRIMARY KEY" appliesTo="SEQUENCE_ID, ORIGINAL_ID, MAPPED_ID" />
+ <Constraint schema="OSEE" id="OSEE_IMPORT_INDEX_MAP_II_FK" type="FOREIGN KEY" appliesTo="SEQUENCE_ID" deferrable="true">
+ <References schema="OSEE" table="OSEE_IMPORT_MAP" column="SEQUENCE_ID" />
+ </Constraint>
+ <Index id="OSEE_IMPORT_INDEX_MAP_IO_IDX" tablespace="osee_index">
+ <AppliesTo id="SEQUENCE_ID"/>
+ <AppliesTo id="ORIGINAL_ID"/>
+ </Index>
+ <Index id="OSEE_IMPORT_INDEX_MAP_IM_IDX" tablespace="osee_index">
+ <AppliesTo id="SEQUENCE_ID"/>
+ <AppliesTo id="MAPPED_ID"/>
+ </Index>
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- -->
+ <!-- Application Server -->
+ <!-- -->
+ <!-- __________________________________________________________ -->
+
+ <Table name="OSEE_SERVER_LOOKUP" schema="OSEE" tablespace="osee_data">
+ <Column id="VERSION_ID" defaultValue="not null" type="VARCHAR" limits="100" />
+ <Column id="SERVER_ADDRESS" defaultValue="not null" type="VARCHAR" limits="255"/>
+ <Column id="PORT" defaultValue="not null" type="INTEGER" />
+ <Column id="ACCEPTS_REQUESTS" defaultValue="not null" type="smallint" />
+ <Column id="START_TIME" defaultValue="not null" type="TIMESTAMP" />
+ <Column id="SERVER_ID" defaultValue="not null" type="VARCHAR" limits="40" />
+ <Constraint schema="OSEE" id="OSEE_SERVER_LOOKUP_PK" type="PRIMARY KEY" appliesTo="SERVER_ADDRESS, PORT, VERSION_ID" />
+ </Table>
+
+ <Table name="OSEE_SESSION" schema="OSEE" tablespace="osee_data">
+ <Column id="MANAGED_BY_SERVER_ID" defaultValue="not null" type="VARCHAR" limits="40" />
+ <Column id="SESSION_ID" defaultValue="not null" type="VARCHAR" limits="28" />
+ <Column id="USER_ID" defaultValue="not null" type="VARCHAR" limits="100"/>
+ <Column id="CLIENT_MACHINE_NAME" defaultValue="not null" type="VARCHAR" limits="100"/>
+ <Column id="CLIENT_ADDRESS" defaultValue="not null" type="VARCHAR" limits="255"/>
+ <Column id="CLIENT_PORT" defaultValue="not null" type="INTEGER" />
+ <Column id="CLIENT_VERSION" defaultValue="not null" type="VARCHAR" limits="100"/>
+ <Column id="CREATED_ON" defaultValue="not null" type="TIMESTAMP" />
+ <Column id="LAST_INTERACTION_DATE" defaultValue="not null" type="TIMESTAMP" />
+ <Column id="LAST_INTERACTION" defaultValue="not null" type="VARCHAR" limits="1000"/>
+ <Constraint schema="OSEE" id="OSEE_SESSION_PK" type="PRIMARY KEY" appliesTo="SESSION_ID" />
+ </Table>
+
+ <!-- __________________________________________________________ -->
+ <!-- Coverage Temp -->
+ <!-- __________________________________________________________ -->
+ <Table name="OSEE_CVG_TESTUNITS">
+ <Column id="NAME_ID" limits="8,0" type="DECIMAL" />
+ <Column id="NAME" limits="255" type="VARCHAR" />
+ <Constraint schema="OSEE" id="CVG_NAME_ID_PK" type="UNIQUE" appliesTo="NAME_ID" />
+ </Table>
+
+</TableConfig>
\ No newline at end of file |