OPENJPA-2554 JPA 2.1 - Schema Generation, patch from Roberto Cortez, doc to update still

git-svn-id: https://svn.apache.org/repos/asf/openjpa/trunk@1770509 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Romain Manni-Bucau 2016-11-19 18:08:44 +00:00
parent bdc1da9423
commit af8ea38f87
14 changed files with 805 additions and 14 deletions

View File

@ -22,6 +22,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.apache.openjpa.conf.SchemaGenerationSource;
import org.apache.openjpa.lib.util.StringUtil;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl;
@ -36,6 +37,19 @@ import org.apache.openjpa.lib.conf.Configurations;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.util.UserException;
import static org.apache.openjpa.conf.SchemaGenerationAction.CREATE;
import static org.apache.openjpa.conf.SchemaGenerationAction.DROP;
import static org.apache.openjpa.conf.SchemaGenerationAction.DROP_AND_CREATE;
import static org.apache.openjpa.conf.SchemaGenerationSource.METADATA;
import static org.apache.openjpa.conf.SchemaGenerationSource.METADATA_THEN_SCRIPT;
import static org.apache.openjpa.conf.SchemaGenerationSource.SCRIPT;
import static org.apache.openjpa.conf.SchemaGenerationSource.SCRIPT_THEN_METADATA;
import static org.apache.openjpa.jdbc.meta.MappingTool.ACTION_ADD;
import static org.apache.openjpa.jdbc.meta.MappingTool.ACTION_DROP;
import static org.apache.openjpa.jdbc.meta.MappingTool.ACTION_SCRIPT_CREATE;
import static org.apache.openjpa.jdbc.meta.MappingTool.ACTION_SCRIPT_DROP;
import static org.apache.openjpa.jdbc.meta.MappingTool.ACTION_SCRIPT_LOAD;
/**
* BrokerFactory type for use with the JDBC runtime.
*
@ -133,6 +147,7 @@ public class JDBCBrokerFactory
*/
protected void synchronizeMappings(ClassLoader loader,
JDBCConfiguration conf) {
mapSchemaGenerationToSynchronizeMappings(conf);
String action = conf.getSynchronizeMappings();
if (StringUtil.isEmpty(action))
return;
@ -163,4 +178,80 @@ public class JDBCBrokerFactory
protected void synchronizeMappings(ClassLoader loader) {
synchronizeMappings(loader, (JDBCConfiguration) getConfiguration());
}
private void mapSchemaGenerationToSynchronizeMappings(JDBCConfiguration conf) {
String actions = "";
if (conf.getDatabaseAction() != null) {
int databaseAction = conf.getDatabaseActionConstant();
if (databaseAction == CREATE) {
actions = generateSchemaCreation(conf);
} else if (databaseAction == DROP) {
actions = generateSchemaDrop(conf);
} else if (databaseAction == DROP_AND_CREATE) {
actions = generateSchemaDropCreate(conf);
}
}
String loadFile = conf.getLoadScriptSource();
if (loadFile != null) {
actions += "," + ACTION_SCRIPT_LOAD;
}
if (actions.length() > 0) {
conf.setSynchronizeMappings("buildSchema(ForeignKeys=true,SchemaAction='" + actions + "')");
}
}
private String generateSchemaCreation(JDBCConfiguration conf) {
if (conf.getCreateScriptTarget() != null) {
return MappingTool.ACTION_ADD;
} else {
int createSource = conf.getCreateSourceConstant();
if (createSource == SchemaGenerationSource.NONE && conf.getCreateScriptSource() != null) {
createSource = SCRIPT;
} else {
createSource = METADATA;
}
return mapGenerationStrategyActions(createSource, ACTION_ADD, ACTION_SCRIPT_CREATE);
}
}
private String generateSchemaDrop(JDBCConfiguration conf) {
if (conf.getDropScriptTarget() != null) {
return MappingTool.ACTION_DROP;
} else {
int dropSource = conf.getDropSourceConstant();
if (dropSource == SchemaGenerationSource.NONE && conf.getDropScriptSource() != null) {
dropSource = SCRIPT;
} else {
dropSource = METADATA;
}
return mapGenerationStrategyActions(dropSource, ACTION_DROP, ACTION_SCRIPT_DROP);
}
}
private String generateSchemaDropCreate(JDBCConfiguration conf) {
if (conf.getCreateScriptTarget() != null && conf.getDropScriptTarget() != null) {
return MappingTool.ACTION_ADD + "," + MappingTool.ACTION_DROP;
} else {
return mapGenerationStrategyActions(conf.getDropSourceConstant(), ACTION_DROP, ACTION_SCRIPT_DROP) + "," +
mapGenerationStrategyActions(conf.getCreateSourceConstant(), ACTION_ADD, ACTION_SCRIPT_CREATE);
}
}
private String mapGenerationStrategyActions(int source, String metadataAction, String scriptAction) {
String actions = "";
if (source == METADATA) {
actions += metadataAction;
} else if (source == SCRIPT) {
actions += scriptAction;
} else if (source == METADATA_THEN_SCRIPT) {
actions += metadataAction + "," + scriptAction;
} else if (source == SCRIPT_THEN_METADATA) {
actions += scriptAction + "," + metadataAction;
} else {
actions += metadataAction;
}
return actions;
}
}

View File

@ -90,6 +90,9 @@ public class MappingTool
public static final String ACTION_VALIDATE = "validate";
public static final String ACTION_EXPORT = "export";
public static final String ACTION_IMPORT = "import";
public static final String ACTION_SCRIPT_CREATE = "scriptCreate";
public static final String ACTION_SCRIPT_DROP = "scriptDrop";
public static final String ACTION_SCRIPT_LOAD = "scriptLoad";
public static final String[] ACTIONS = new String[]{
ACTION_ADD,
@ -100,6 +103,9 @@ public class MappingTool
ACTION_VALIDATE,
ACTION_EXPORT,
ACTION_IMPORT,
ACTION_SCRIPT_CREATE,
ACTION_SCRIPT_DROP,
ACTION_SCRIPT_LOAD,
};
private static final Localizer _loc = Localizer.forPackage(MappingTool.class);
@ -502,7 +508,26 @@ public class MappingTool
if (!SCHEMA_ACTION_NONE.equals(schemaActions[i])
&& (_schemaWriter == null || (_schemaTool != null
&& _schemaTool.getWriter() != null))) {
SchemaTool tool = newSchemaTool(schemaActions[i]);
SchemaTool tool;
if (schemaActions[i].equals(ACTION_SCRIPT_CREATE) ||
schemaActions[i].equals(ACTION_SCRIPT_DROP) ||
schemaActions[i].equals(ACTION_SCRIPT_LOAD)) {
tool = newSchemaTool(SchemaTool.ACTION_EXECUTE_SCRIPT);
} else {
tool = newSchemaTool(schemaActions[i]);
}
if (schemaActions[i].equals(ACTION_ADD) && _conf.getCreateScriptTarget() != null) {
tool.setWriter(new PrintWriter(_conf.getCreateScriptTarget()));
tool.setIndexes(true);
tool.setForeignKeys(true);
tool.setSequences(true);
}
if (schemaActions[i].equals(ACTION_DROP) && _conf.getDropScriptTarget() != null) {
tool.setWriter(new PrintWriter(_conf.getDropScriptTarget()));
}
// configure the tool with additional settings
if (flags != null) {
@ -513,6 +538,18 @@ public class MappingTool
tool.setSQLTerminator(flags.sqlTerminator);
}
switch (schemaActions[i]) {
case ACTION_SCRIPT_CREATE:
tool.setScriptToExecute(_conf.getCreateScriptSource());
break;
case ACTION_SCRIPT_DROP:
tool.setScriptToExecute(_conf.getDropScriptSource());
break;
case ACTION_SCRIPT_LOAD:
tool.setScriptToExecute(_conf.getLoadScriptSource());
break;
}
tool.setSchemaGroup(getSchemaGroup());
tool.run();
tool.record();

View File

@ -18,23 +18,30 @@
*/
package org.apache.openjpa.jdbc.schema;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.security.AccessController;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.StringUtil;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
@ -74,6 +81,7 @@ public class SchemaTool {
public static final String ACTION_IMPORT = "import";
public static final String ACTION_EXPORT = "export";
public static final String ACTION_DELETE_TABLE_CONTENTS = "deleteTableContents";
public static final String ACTION_EXECUTE_SCRIPT = "executeScript";
public static final String[] ACTIONS = new String[]{
ACTION_ADD,
@ -88,6 +96,7 @@ public class SchemaTool {
ACTION_IMPORT,
ACTION_EXPORT,
ACTION_DELETE_TABLE_CONTENTS,
ACTION_EXECUTE_SCRIPT
};
protected static final Localizer _loc = Localizer.forPackage(SchemaTool.class);
@ -110,7 +119,8 @@ public class SchemaTool {
private SchemaGroup _db = null;
protected boolean _fullDB = false;
protected String _sqlTerminator = ";";
protected String _scriptToExecute = null;
/**
* Default constructor. Tools constructed this way will not have an
* action, so the {@link #run()} method will be a no-op.
@ -313,6 +323,10 @@ public class SchemaTool {
_sqlTerminator = t;
}
public void setScriptToExecute(String scriptToExecute) {
_scriptToExecute = scriptToExecute;
}
/**
* Return the schema group the tool will act on.
*/
@ -357,6 +371,9 @@ public class SchemaTool {
dropDB();
else if (ACTION_DELETE_TABLE_CONTENTS.equals(_action))
deleteTableContents();
else if (ACTION_EXECUTE_SCRIPT.equals(_action)) {
executeScript();
}
}
/**
@ -463,6 +480,54 @@ public class SchemaTool {
}
}
protected void executeScript() throws SQLException {
if (_scriptToExecute == null) {
_log.warn(_loc.get("generating-execute-script-not-defined"));
return;
}
URL url = AccessController.doPrivileged(
J2DoPrivHelper.getResourceAction(_conf.getClassResolverInstance().
getClassLoader(SchemaTool.class, null), _scriptToExecute));
if (url == null) {
_log.error(_loc.get("generating-execute-script-not-found", _scriptToExecute));
return;
}
_log.info(_loc.get("generating-execute-script", _scriptToExecute));
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String sql;
List<String> script = new ArrayList<String>();
while ((sql = reader.readLine()) != null) {
sql = sql.trim();
if (sql.startsWith("--") || sql.startsWith("/*") || sql.startsWith("//")) {
continue;
}
int semiColonPosition = sql.indexOf(";");
if (semiColonPosition != -1) {
sql = sql.substring(0, semiColonPosition);
}
script.add(sql);
}
executeSQL(script.toArray(new String[script.size()]));
} catch (IOException e) {
_log.error(e.getMessage(), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
_log.error(e.getMessage(), e);
}
}
}
/**
* Record the changes made to the DB in the current {@link SchemaFactory}.
*/
@ -490,9 +555,11 @@ public class SchemaTool {
for (int i = 0; i < schemas.length; i++) {
seqs = schemas[i].getSequences();
for (int j = 0; j < seqs.length; j++) {
if (considerDatabaseState && db.findSequence(schemas[i], seqs[j].getQualifiedPath()) !=
null)
continue;
if (considerDatabaseState && db.findSequence(schemas[i], seqs[j].getQualifiedPath()) != null) {
if (_writer == null) {
continue;
}
}
if (createSequence(seqs[j])) {
schema = db.getSchema(seqs[j].getSchemaIdentifier());
@ -567,8 +634,11 @@ public class SchemaTool {
for (int i = 0; i < schemas.length; i++) {
tabs = schemas[i].getTables();
for (int j = 0; j < tabs.length; j++) {
if (considerDatabaseState && db.findTable(schemas[i], tabs[j].getQualifiedPath()) != null)
continue;
if (considerDatabaseState && db.findTable(schemas[i], tabs[j].getQualifiedPath()) != null) {
if (_writer == null) {
continue;
}
}
if (createTable(tabs[j])) {
newTables.add(tabs[j]);
@ -618,8 +688,11 @@ public class SchemaTool {
tabs = schemas[i].getTables();
for (int j = 0; j < tabs.length; j++) {
// create unique constraints only on new tables
if (!newTables.contains(tabs[j]))
continue;
if (!newTables.contains(tabs[j])) {
if (_writer == null) {
continue;
}
}
uniques = tabs[j].getUniques();
if (uniques == null || uniques.length == 0)
@ -643,8 +716,11 @@ public class SchemaTool {
for (int j = 0; j < tabs.length; j++) {
// create foreign keys on new tables even if fks
// have been turned off
if (!_fks && !newTables.contains(tabs[j]))
continue;
if (!_fks && !newTables.contains(tabs[j])) {
if (_writer == null) {
continue;
}
}
fks = tabs[j].getForeignKeys();
if (considerDatabaseState) {
@ -822,6 +898,10 @@ public class SchemaTool {
else
_log.warn(_loc.get("drop-seq", seqs[j]));
}
if (_writer != null) {
dropSequence(seqs[j]);
}
}
}
}
@ -846,8 +926,12 @@ public class SchemaTool {
}
dbTable = db.findTable(tabs[j]);
if (dbTable == null)
if (dbTable == null) {
if (_writer != null) {
drops.add(tabs[j]);
}
continue;
}
dbCols = dbTable.getColumns();
for (int k = 0; k < dbCols.length; k++) {

View File

@ -147,6 +147,9 @@ generating-primary: Reading primary keys for table "{1}"
generating-indexes: Reading indexes for table "{1}"
generating-foreign: Reading foreign keys for table "{1}"
generating-sequences: Reading sequences for schema "{0}"
generating-execute-script: Executing script "{0}".
generating-execute-script-not-defined: A script needs to be indicated to execute, but no script was set in setScriptToExecute.
generating-execute-script-not-found: Could not find script to execute "{0}"
no-custom-ds: use a custom DataSource
delete-table-contents: An error occurred while attempting to delete all \
records from all mapped tables.

View File

@ -1788,7 +1788,7 @@ public interface OpenJPAConfiguration
/**
* Sets the {@link EncryptionProvider}.
*
*
*/
public void setEncryptionProvider(String className);
@ -1983,5 +1983,31 @@ public interface OpenJPAConfiguration
* @since 2.4.2
*/
public void setUseTCCLinSelectNew(Boolean useTcclForSelectNew);
public String getDatabaseAction();
public int getDatabaseActionConstant();
String getScriptsAction();
int getScriptsActionConstant();
String getCreateSource();
int getCreateSourceConstant();
String getDropSource();
int getDropSourceConstant();
String getCreateScriptSource();
String getDropScriptSource();
String getCreateScriptTarget();
String getDropScriptTarget();
String getLoadScriptSource();
}

View File

@ -178,6 +178,17 @@ public class OpenJPAConfigurationImpl
public BooleanValue postLoadOnMerge;
public BooleanValue optimizeIdCopy;
public BooleanValue useTcclForSelectNew;
// JPA Properties
public IntValue databaseAction;
public IntValue scriptsAction;
public IntValue createSource;
public IntValue dropSource;
public StringValue createScriptSource;
public StringValue dropScriptSource;
public StringValue createScriptTarget;
public StringValue dropScriptTarget;
public StringValue loadScriptSource;
// custom values
public BrokerFactoryValue brokerFactoryPlugin;
@ -406,7 +417,58 @@ public class OpenJPAConfigurationImpl
optimizeIdCopy = addBoolean("OptimizeIdCopy");
optimizeIdCopy.setDefault("false");
optimizeIdCopy.set(false);
databaseAction = addInt("javax.persistence.schema-generation.database.action");
aliases = new String[] {
"none", String.valueOf(SchemaGenerationAction.NONE),
"create", String.valueOf(SchemaGenerationAction.CREATE),
"drop-and-create", String.valueOf(SchemaGenerationAction.DROP_AND_CREATE),
"drop", String.valueOf(SchemaGenerationAction.DROP)
};
databaseAction.setAliases(aliases);
databaseAction.setDefault(aliases[0]);
databaseAction.setAliasListComprehensive(true);
scriptsAction = addInt("javax.persistence.schema-generation.scripts.action");
aliases = new String[] {
"none", String.valueOf(SchemaGenerationAction.NONE),
"create", String.valueOf(SchemaGenerationAction.CREATE),
"drop-and-create", String.valueOf(SchemaGenerationAction.DROP_AND_CREATE),
"drop", String.valueOf(SchemaGenerationAction.DROP)
};
scriptsAction.setAliases(aliases);
scriptsAction.setDefault(aliases[0]);
scriptsAction.setAliasListComprehensive(true);
createSource = addInt("javax.persistence.schema-generation.create-source");
aliases = new String[] {
"none", String.valueOf(SchemaGenerationSource.NONE),
"metadata", String.valueOf(SchemaGenerationSource.METADATA),
"script", String.valueOf(SchemaGenerationSource.SCRIPT),
"metadata-then-script", String.valueOf(SchemaGenerationSource.METADATA_THEN_SCRIPT),
"script-then-metadata", String.valueOf(SchemaGenerationSource.SCRIPT_THEN_METADATA)
};
createSource.setAliases(aliases);
createSource.setDefault(aliases[0]);
createSource.setAliasListComprehensive(true);
dropSource = addInt("javax.persistence.schema-generation.drop-source");
aliases = new String[] {
"metadata", String.valueOf(SchemaGenerationSource.METADATA),
"script", String.valueOf(SchemaGenerationSource.SCRIPT),
"metadata-then-script", String.valueOf(SchemaGenerationSource.METADATA_THEN_SCRIPT),
"script-then-metadata", String.valueOf(SchemaGenerationSource.SCRIPT_THEN_METADATA)
};
dropSource.setAliases(aliases);
dropSource.setDefault(aliases[0]);
dropSource.setAliasListComprehensive(true);
createScriptSource = addString("javax.persistence.schema-generation.create-script-source");
dropScriptSource = addString("javax.persistence.schema-generation.drop-script-source");
createScriptTarget = addString("javax.persistence.schema-generation.scripts.create-target");
dropScriptTarget = addString("javax.persistence.schema-generation.scripts.drop-target");
loadScriptSource = addString("javax.persistence.sql-load-script-source");
autoClear = addInt("AutoClear");
aliases =
new String[] { "datastore",
@ -1880,6 +1942,58 @@ public class OpenJPAConfigurationImpl
}
}
public String getDatabaseAction() {
return databaseAction.getString();
}
public int getDatabaseActionConstant() {
return databaseAction.get();
}
public String getScriptsAction() {
return scriptsAction.getString();
}
public int getScriptsActionConstant() {
return scriptsAction.get();
}
public String getCreateSource() {
return createSource.getString();
}
public int getCreateSourceConstant() {
return createSource.get();
}
public String getDropSource() {
return dropSource.getString();
}
public int getDropSourceConstant() {
return dropSource.get();
}
public String getCreateScriptSource() {
return createScriptSource.getString();
}
public String getDropScriptSource() {
return dropScriptSource.getString();
}
public String getCreateScriptTarget() {
return createScriptTarget.getString();
}
public String getDropScriptTarget() {
return dropScriptTarget.getString();
}
public String getLoadScriptSource() {
return loadScriptSource.getString();
}
@Override
public boolean getUseTCCLinSelectNew() {
return useTcclForSelectNew.get();

View File

@ -0,0 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.conf;
/**
* @author Roberto Cortez
*/
public interface SchemaGenerationAction {
public static final int NONE = 0;
public static final int CREATE = 1;
public static final int DROP_AND_CREATE = 2;
public static final int DROP = 3;
}

View File

@ -0,0 +1,34 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.conf;
/**
* @author Roberto Cortez
*/
public interface SchemaGenerationSource {
public static final int NONE = 0;
public static final int METADATA = 1;
public static final int SCRIPT = 2;
public static final int METADATA_THEN_SCRIPT = 3;
public static final int SCRIPT_THEN_METADATA = 4;
}

View File

@ -0,0 +1,339 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.persistence.jdbc.schema;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.jdbc.meta.MappingTool;
import org.apache.openjpa.jdbc.schema.Schema;
import org.apache.openjpa.jdbc.schema.SchemaGroup;
import org.apache.openjpa.jdbc.schema.SchemaTool;
import org.apache.openjpa.jdbc.schema.Table;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI;
import org.apache.openjpa.persistence.jdbc.common.apps.InvertA;
import org.apache.openjpa.persistence.jdbc.kernel.BaseJDBCTest;
import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import static org.apache.openjpa.jdbc.identifier.DBIdentifier.newSchema;
import static org.apache.openjpa.jdbc.identifier.DBIdentifier.newTable;
import static org.apache.openjpa.jdbc.identifier.QualifiedDBIdentifier.getPath;
/**
* @author Roberto Cortez
*/
public class TestSchemaGenerationProperties extends BaseJDBCTest {
private static final String[] TABLES_NAME = {
"AUTOINCPC1",
"AUTOINCPC3",
"CONJOINPC4",
"CONJOINPC5",
"CUSTMAPPC",
"DFGTEST",
"EAGERPC",
"EAGERPCSUB",
"HELPERPC",
"HELPERPC2",
"HELPERPC3",
"INVERTA",
"INVERTB",
"EAGEROUTERJOINPC"
};
public TestSchemaGenerationProperties(String name) {
super(name);
}
@Override
protected String getPersistenceUnitName() {
return "TestConv";
}
@Override
protected void addProperties(Map map) {}
@Override
public void setUp() throws Exception {
super.setUp();
OpenJPAEntityManagerFactory pmf = getEmf(new HashMap());
pmf.createEntityManager();
JDBCConfiguration conf = (JDBCConfiguration) ((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration();
MappingTool tool = new MappingTool(conf, "drop", false);
SchemaTool schemaTool = new SchemaTool(conf, "drop");
schemaTool.setSchemaGroup(tool.getSchemaGroup());
schemaTool.run();
}
// TODO - Add validation when source uses script but no script is provided?.
public void testSchemaGenMetadataDrop() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNull("Table " + tableName + " should not exist in the DB.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenMetadataCreate() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "create");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenMetadataDropAndCreate() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop-and-create");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenScriptDrop() throws Exception {
testSchemaGenMetadataCreate();
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop");
properties.put("javax.persistence.schema-generation.drop-source", "script");
properties.put("javax.persistence.schema-generation.drop-script-source",
"org/apache/openjpa/persistence/jdbc/schema/drop.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNull("Table " + tableName + " should not exist in the DB.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenScriptCreate() throws Exception {
testSchemaGenMetadataDrop();
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "create");
properties.put("javax.persistence.schema-generation.create-source", "script");
properties.put("javax.persistence.schema-generation.create-script-source",
"org/apache/openjpa/persistence/jdbc/schema/create.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenScriptDropAndCreate() throws Exception {
testSchemaGenMetadataCreate();
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop-and-create");
properties.put("javax.persistence.schema-generation.drop-source", "script");
properties.put("javax.persistence.schema-generation.drop-script-source",
"org/apache/openjpa/persistence/jdbc/schema/drop.sql");
properties.put("javax.persistence.schema-generation.create-source", "script");
properties.put("javax.persistence.schema-generation.create-script-source",
"org/apache/openjpa/persistence/jdbc/schema/create.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenMetadataThenScriptDropAndCreate() throws Exception {
try {
OpenJPAEntityManagerFactory pmf = getEmf();
pmf.createEntityManager();
JDBCConfiguration conf = (JDBCConfiguration) ((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration();
SchemaTool schemaTool = new SchemaTool(conf, SchemaTool.ACTION_EXECUTE_SCRIPT);
schemaTool.setScriptToExecute("org/apache/openjpa/persistence/jdbc/schema/create-after-metadata.sql");
schemaTool.run();
} catch (SQLException e) {}
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop-and-create");
properties.put("javax.persistence.schema-generation.drop-source", "metadata-then-script");
properties.put("javax.persistence.schema-generation.drop-script-source",
"org/apache/openjpa/persistence/jdbc/schema/drop-after-metadata.sql");
properties.put("javax.persistence.schema-generation.create-source", "metadata-then-script");
properties.put("javax.persistence.schema-generation.create-script-source",
"org/apache/openjpa/persistence/jdbc/schema/create-after-metadata.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
assertNotNull("Table " + "CREATE_AFTER_METADATA" + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable("CREATE_AFTER_METADATA"))));
}
public void testSchemaGenNoCreateSourceSpecifiedAndCreateScriptSourceSpecified() throws Exception {
try {
OpenJPAEntityManagerFactory pmf = getEmf();
pmf.createEntityManager();
JDBCConfiguration conf = (JDBCConfiguration) ((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration();
SchemaTool schemaTool = new SchemaTool(conf, SchemaTool.ACTION_EXECUTE_SCRIPT);
schemaTool.setScriptToExecute("org/apache/openjpa/persistence/jdbc/schema/drop-after-metadata.sql");
schemaTool.run();
} catch (SQLException e) {}
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "create");
properties.put("javax.persistence.schema-generation.create-script-source",
"org/apache/openjpa/persistence/jdbc/schema/create-after-metadata.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
assertNotNull("Table " + "CREATE_AFTER_METADATA" + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable("CREATE_AFTER_METADATA"))));
}
public void testSchemaGenNoCreateSourceAndCreateScriptSourceSpecified() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "create");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenNoDropSourceSpecifiedAndDropScriptSourceSpecified() throws Exception {
testSchemaGenMetadataCreate();
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop");;
properties.put("javax.persistence.schema-generation.drop-script-source",
"org/apache/openjpa/persistence/jdbc/schema/drop.sql");
SchemaGroup dbSchemaGroup = getSchemaGroup(properties);
for (String tableName : TABLES_NAME) {
assertNull("Table " + tableName + " should not exist in the DB.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
}
public void testSchemaGenScriptLoad() throws Exception {
testSchemaGenMetadataDropAndCreate();
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.sql-load-script-source",
"org/apache/openjpa/persistence/jdbc/schema/load.sql");
OpenJPAEntityManagerFactory pmf = getEmf(properties);
OpenJPAEntityManager entityManager = pmf.createEntityManager();
JDBCConfiguration conf = (JDBCConfiguration) ((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration();
SchemaTool schemaTool = new SchemaTool(conf);
SchemaGroup dbSchemaGroup = schemaTool.getDBSchemaGroup();
for (String tableName : TABLES_NAME) {
assertNotNull("Table " + tableName + " should have been created in the DB, but does not exists.",
dbSchemaGroup.findTable(getPath(newTable(tableName))));
}
InvertA invertA = entityManager.find(InvertA.class, 1);
assertEquals(1, invertA.getId());
assertEquals("script load test", invertA.getTest());
}
public void testSchemaGenOutputScriptCreate() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "create");
properties.put("javax.persistence.schema-generation.scripts.create-target",
"target/create-db-output.sql");
getEmf(properties).createEntityManager();
File createFile = new File("target/create-db-output.sql");
assertTrue(createFile.exists());
assertTrue(createFile.length() > 0);
}
public void testSchemaGenOutputScriptDrop() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop");
properties.put("javax.persistence.schema-generation.scripts.drop-target",
"target/drop-db-output.sql");
getEmf(properties).createEntityManager();
File dropFile = new File("target/drop-db-output.sql");
assertTrue(dropFile.exists());
assertTrue(dropFile.length() > 0);
}
public void testSchemaGenOutputScriptDropAndCreate() throws Exception {
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.schema-generation.database.action", "drop-and-create");
properties.put("javax.persistence.schema-generation.scripts.create-target",
"target/create-db-output.sql");
properties.put("javax.persistence.schema-generation.scripts.drop-target",
"target/drop-db-output.sql");
getEmf(properties).createEntityManager();
File createFile = new File("target/create-db-output.sql");
assertTrue(createFile.exists());
assertTrue(createFile.length() > 0);
File dropFile = new File("target/drop-db-output.sql");
assertTrue(dropFile.exists());
assertTrue(dropFile.length() > 0);
}
private SchemaGroup getSchemaGroup(Map<String, String> properties) {
OpenJPAEntityManagerFactory pmf = getEmf(properties);
pmf.createEntityManager();
JDBCConfiguration conf = (JDBCConfiguration) ((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration();
SchemaTool schemaTool = new SchemaTool(conf);
return schemaTool.getDBSchemaGroup();
}
}

View File

@ -0,0 +1 @@
CREATE TABLE CREATE_AFTER_METADATA (ID INTEGER NOT NULL, TEST VARCHAR(35));

View File

@ -0,0 +1,14 @@
CREATE TABLE AUTOINCPC1 (ID INTEGER NOT NULL, STRNGFLD VARCHAR(50), DTYPE VARCHAR(255), ONEONE_ID INTEGER, INTFIELD INTEGER, CONSTRAINT SQL150111133630290 PRIMARY KEY (ID));
CREATE TABLE AUTOINCPC3 (ID BIGINT NOT NULL, STRNGFLD VARCHAR(50), ONEONE_ID BIGINT, CONSTRAINT SQL150111133630380 PRIMARY KEY (ID));
CREATE TABLE CONJOINPC4 (ID INTEGER NOT NULL, MANYTOMANY BLOB, NAME VARCHAR(50), ONETOONE1_ID INTEGER, CONSTRAINT SQL150111133630400 PRIMARY KEY (ID));
CREATE TABLE CONJOINPC5 (ID INTEGER NOT NULL, NAME VARCHAR(255), CONSTRAINT SQL150111133630420 PRIMARY KEY (ID));
CREATE TABLE CUSTMAPPC (ID INTEGER NOT NULL, FEMALE SMALLINT, NAME VARCHAR(50), CONSTRAINT SQL150111133630430 PRIMARY KEY (ID));
CREATE TABLE DFGTEST (ID BIGINT NOT NULL, DFGFIELD INTEGER, NONDFGFIELD INTEGER, CONSTRAINT SQL150111133630450 PRIMARY KEY (ID));
CREATE TABLE EAGEROUTERJOINPC (ID BIGINT NOT NULL, NAME VARCHAR(255), HELPER BLOB, CONSTRAINT SQL150111133630460 PRIMARY KEY (ID));
CREATE TABLE EAGERPC (ID INTEGER NOT NULL, STRNGFLD VARCHAR(50), EAGER_ID INTEGER, EAGSUB INTEGER, HELPER_ID INTEGER, RECURSE_ID INTEGER, CONSTRAINT SQL150111133630470 PRIMARY KEY (ID));
CREATE TABLE EAGERPCSUB (ID INTEGER NOT NULL, INTFIELD INTEGER, CONSTRAINT SQL150111133630480 PRIMARY KEY (ID));
CREATE TABLE HELPERPC (ID INTEGER NOT NULL, STRNGFLD VARCHAR(50), EAGER_ID INTEGER, HELPER BLOB, CONSTRAINT SQL150111133630500 PRIMARY KEY (ID));
CREATE TABLE HELPERPC2 (ID INTEGER NOT NULL, STRNGFLD VARCHAR(50), HELPER_ID INTEGER, CONSTRAINT SQL150111133630510 PRIMARY KEY (ID));
CREATE TABLE HELPERPC3 (ID INTEGER NOT NULL, STRNGFLD VARCHAR(50), DTYPE VARCHAR(255), INTFIELD INTEGER, CONSTRAINT SQL150111133630520 PRIMARY KEY (ID));
CREATE TABLE INVERTA (ID INTEGER NOT NULL, TEST VARCHAR(35), INVERTB_ID INTEGER, CONSTRAINT SQL150111133630530 PRIMARY KEY (ID));
CREATE TABLE INVERTB (ID INTEGER NOT NULL, TEST VARCHAR(35), INVERTA_ID INTEGER, CONSTRAINT SQL150111133630540 PRIMARY KEY (ID));

View File

@ -0,0 +1 @@
DROP TABLE CREATE_AFTER_METADATA;

View File

@ -0,0 +1,14 @@
DROP TABLE AUTOINCPC1;
DROP TABLE AUTOINCPC3;
DROP TABLE CONJOINPC4;
DROP TABLE CONJOINPC5;
DROP TABLE CUSTMAPPC;
DROP TABLE DFGTEST;
DROP TABLE EAGEROUTERJOINPC;
DROP TABLE EAGERPC;
DROP TABLE EAGERPCSUB;
DROP TABLE HELPERPC;
DROP TABLE HELPERPC2;
DROP TABLE HELPERPC3;
DROP TABLE INVERTA;
DROP TABLE INVERTB;

View File

@ -0,0 +1 @@
INSERT INTO INVERTA (ID, TEST) VALUES (1, 'script load test');