You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cayenne.apache.org by aa...@apache.org on 2016/12/14 18:29:51 UTC
[2/9] cayenne git commit: New DbLoader for dbsync utils - loading
process split in independent small steps - DbLoader always return new DataMap,
it doesn't accept it from outside
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbLoaderDelegate.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbLoaderDelegate.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbLoaderDelegate.java
new file mode 100644
index 0000000..ae694eb
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbLoaderDelegate.java
@@ -0,0 +1,63 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DbRelationship;
+import org.apache.cayenne.map.ObjEntity;
+
+/**
+ * Defines API for progress tracking and altering the folow of reverse-engineering.
+ */
+public interface DbLoaderDelegate {
+
+ void dbEntityAdded(DbEntity entity);
+
+ void dbEntityRemoved(DbEntity entity);
+
+ /**
+ * Called before relationship loading for a {@link DbEntity}.
+ *
+ * @param entity DbEntity for which {@link DbRelationship} is about to be loaded.
+ * @return true in case you want process relationships for this entity, false otherwise.
+ */
+ boolean dbRelationship(DbEntity entity);
+
+ /**
+ * Called before relationship will be added into db-entity but after it was loaded from db
+ *
+ * @param entity
+ * @return true in case you want add this relationship into entity
+ * false otherwise
+ */
+ boolean dbRelationshipLoaded(DbEntity entity, DbRelationship relationship);
+
+ /**
+ * @deprecated since 4.0 no longer invoked as DbLoader2 does not deal with object layer anymore.
+ */
+ @Deprecated
+ void objEntityAdded(ObjEntity entity);
+
+ /**
+ * @deprecated since 4.0 no longer invoked as DbLoader2 does not deal with object layer anymore.
+ */
+ @Deprecated
+ void objEntityRemoved(ObjEntity entity);
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbRelationshipDetected.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbRelationshipDetected.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbRelationshipDetected.java
new file mode 100644
index 0000000..5a8b8cd
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DbRelationshipDetected.java
@@ -0,0 +1,54 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+
+import org.apache.cayenne.map.DbRelationship;
+
+/**
+ * A subclass of {@link DbRelationship} to hold some extra runtime information.
+ */
+// TODO: dirty ... can we lookup fkName via joins?
+public class DbRelationshipDetected extends DbRelationship {
+
+ private String fkName;
+
+ public DbRelationshipDetected(String uniqueRelName) {
+ super(uniqueRelName);
+ }
+
+ public DbRelationshipDetected() {
+ }
+
+ /**
+ * Get the name of the underlying foreign key. Typically FK_NAME from jdbc metadata.
+ */
+ public String getFkName() {
+ return fkName;
+ }
+
+ /**
+ * Set the name of the underlying foreign key. Typically FK_NAME from jdbc metadata.
+ */
+ public void setFkName(String fkName) {
+ this.fkName = fkName;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DefaultDbLoaderDelegate.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DefaultDbLoaderDelegate.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DefaultDbLoaderDelegate.java
new file mode 100644
index 0000000..607bd2c
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/DefaultDbLoaderDelegate.java
@@ -0,0 +1,65 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import org.apache.cayenne.dbsync.reverse.dbload.DbLoaderDelegate;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DbRelationship;
+import org.apache.cayenne.map.ObjEntity;
+
+/**
+ * A noop {@link DbLoaderDelegate}.
+ *
+ * @since 4.0
+ */
+public class DefaultDbLoaderDelegate implements DbLoaderDelegate {
+
+ @Override
+ public void dbEntityAdded(DbEntity entity) {
+
+ }
+
+ @Override
+ public void dbEntityRemoved(DbEntity entity) {
+
+ }
+
+ @Override
+ public boolean dbRelationship(DbEntity entity) {
+ return true;
+ }
+
+ @Override
+ public boolean dbRelationshipLoaded(DbEntity entity, DbRelationship relationship) {
+ return true;
+ }
+
+ @Deprecated
+ @Override
+ public void objEntityAdded(ObjEntity entity) {
+
+ }
+
+ @Deprecated
+ @Override
+ public void objEntityRemoved(ObjEntity entity) {
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/EntityLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/EntityLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/EntityLoader.java
new file mode 100644
index 0000000..bbccc15
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/EntityLoader.java
@@ -0,0 +1,106 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.dbsync.reverse.filters.CatalogFilter;
+import org.apache.cayenne.dbsync.reverse.filters.SchemaFilter;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DetectedDbEntity;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+class EntityLoader extends PerCatalogAndSchemaLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(EntityLoader.class);
+
+ private final String[] types;
+
+ EntityLoader(DbAdapter adapter, DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(adapter, config, delegate);
+ types = getTableTypes();
+ }
+
+ @Override
+ protected ResultSet getResultSet(String catalogName, String schemaName, DatabaseMetaData metaData) throws SQLException {
+ return metaData.getTables(catalogName, schemaName, WILDCARD, types);
+ }
+
+ @Override
+ protected void processResultSet(CatalogFilter catalog, SchemaFilter schema, DbLoadDataStore map, ResultSet rs) throws SQLException {
+ String name = rs.getString("TABLE_NAME");
+ String catalogName = rs.getString("TABLE_CAT");
+ String schemaName = rs.getString("TABLE_SCHEM");
+
+ // Oracle 9i and newer has a nifty recycle bin feature...
+ // but we don't want dropped tables to be included here;
+ // in fact they may even result in errors on reverse engineering
+ // as their names have special chars like "/", etc.
+ // So skip them all together (it's about "name == null" check)
+ if (name == null || !schema.tables.isIncludeTable(name)) {
+ return;
+ }
+
+ if (!(catalog.name == null || catalog.name.equals(catalogName))
+ || !(schema.name == null || schema.name.equals(schemaName))) {
+ LOGGER.error(catalogName + "." + schema + "." + schemaName + " wrongly loaded for catalog/schema : "
+ + catalog.name + "." + schema.name);
+ return;
+ }
+
+ DetectedDbEntity table = new DetectedDbEntity(name);
+ table.setCatalog(catalogName);
+ table.setSchema(schemaName);
+ addDbEntityToMap(table, map);
+ }
+
+ private void addDbEntityToMap(DetectedDbEntity table, DbLoadDataStore map) {
+ DbEntity oldEnt = map.addDbEntitySafe(table);
+ if (oldEnt != null) {
+ LOGGER.debug("Overwrite DbEntity: " + oldEnt.getName());
+ delegate.dbEntityRemoved(oldEnt);
+ }
+ delegate.dbEntityAdded(table);
+ }
+
+ private String[] getTableTypes() {
+ String[] configTypes = config.getTableTypes();
+ if (configTypes != null && configTypes.length > 0) {
+ return configTypes;
+ }
+
+ List<String> list = new ArrayList<>(2);
+ String viewType = adapter.tableTypeForView();
+ if (viewType != null) {
+ list.add(viewType);
+ }
+ String tableType = adapter.tableTypeForTable();
+ if (tableType != null) {
+ list.add(tableType);
+ }
+ return list.toArray(new String[0]);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKey.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKey.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKey.java
new file mode 100644
index 0000000..a288fe8
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKey.java
@@ -0,0 +1,220 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import org.apache.cayenne.util.EqualsBuilder;
+import org.apache.cayenne.util.HashCodeBuilder;
+import org.apache.commons.lang.builder.CompareToBuilder;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+/**
+ * A representation of relationship between two tables in database. It can be used for creating names
+ * for relationships.
+ *
+ * @since 4.0
+ */
+public class ExportedKey implements Comparable {
+
+ private final KeyData pk;
+ private final KeyData fk;
+ private final short keySeq;
+
+ /**
+ * Extracts data from a resultset pointing to a exported key to
+ * ExportedKey class instance
+ *
+ * @param rs ResultSet pointing to a exported key, fetched using
+ * DataBaseMetaData.getExportedKeys(...)
+ */
+ public ExportedKey(ResultSet rs) throws SQLException {
+ String pkCatalog = rs.getString("PKTABLE_CAT");
+ String pkSchema = rs.getString("PKTABLE_SCHEM");
+ String pkTable = rs.getString("PKTABLE_NAME");
+ String pkColumn = rs.getString("PKCOLUMN_NAME");
+ String pkName = rs.getString("PK_NAME");
+ pk = new KeyData(pkCatalog, pkSchema, pkTable, pkColumn, pkName);
+
+ String fkCatalog = rs.getString("FKTABLE_CAT");
+ String fkSchema = rs.getString("FKTABLE_SCHEM");
+ String fkTable = rs.getString("FKTABLE_NAME");
+ String fkColumn = rs.getString("FKCOLUMN_NAME");
+ String fkName = rs.getString("FK_NAME");
+ fk = new KeyData(fkCatalog, fkSchema, fkTable, fkColumn, fkName);
+
+ this.keySeq = rs.getShort("KEY_SEQ");
+ }
+
+ public KeyData getPk() {
+ return pk;
+ }
+
+ public KeyData getFk() {
+ return fk;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (obj.getClass() != getClass()) {
+ return false;
+ }
+ ExportedKey rhs = (ExportedKey) obj;
+ return new EqualsBuilder()
+ .append(this.pk, rhs.pk)
+ .append(this.fk, rhs.fk)
+ .append(this.keySeq, rhs.keySeq)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder()
+ .append(pk)
+ .append(fk)
+ .append(keySeq)
+ .toHashCode();
+ }
+
+ @Override
+ public int compareTo(Object obj) {
+ if (obj == null || !obj.getClass().equals(getClass())) {
+ throw new IllegalArgumentException();
+ }
+ if (obj == this) {
+ return 0;
+ }
+
+ ExportedKey rhs = (ExportedKey) obj;
+ return new CompareToBuilder()
+ .append(pk, rhs.pk)
+ .append(fk, rhs.fk)
+ .append(keySeq, rhs.keySeq)
+ .toComparison();
+ }
+
+ @Override
+ public String toString() {
+ return getStrKey() + " # " + keySeq;
+ }
+
+ public String getStrKey() {
+ return pk + " <- " + fk;
+ }
+
+ public static class KeyData implements Comparable {
+ private final String catalog;
+ private final String schema;
+ private final String table;
+ private final String column;
+ private final String name;
+
+ private KeyData(String catalog, String schema, String table, String column, String name) {
+ this.catalog = catalog;
+ this.schema = schema;
+ this.table = table;
+ this.column = column;
+ this.name = name;
+ }
+
+ public String getCatalog() {
+ return catalog;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ public String getTable() {
+ return table;
+ }
+
+ public String getColumn() {
+ return column;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return catalog + "." + schema + "." + table + "." + column;
+ }
+
+ @Override
+ public int compareTo(Object obj) {
+ if (obj == null || !obj.getClass().equals(getClass())) {
+ throw new IllegalArgumentException();
+ }
+ if (obj == this) {
+ return 0;
+ }
+
+ KeyData rhs = (KeyData) obj;
+ return new CompareToBuilder()
+ .append(catalog, rhs.catalog)
+ .append(schema, rhs.schema)
+ .append(table, rhs.table)
+ .append(column, rhs.column)
+ .append(name, rhs.name)
+ .toComparison();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (obj.getClass() != getClass()) {
+ return false;
+ }
+ KeyData rhs = (KeyData) obj;
+ return new EqualsBuilder()
+ .append(this.catalog, rhs.catalog)
+ .append(this.schema, rhs.schema)
+ .append(this.table, rhs.table)
+ .append(this.column, rhs.column)
+ .append(this.name, rhs.name)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder()
+ .append(catalog)
+ .append(schema)
+ .append(table)
+ .append(column)
+ .append(name)
+ .toHashCode();
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKeyLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKeyLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKeyLoader.java
new file mode 100644
index 0000000..779218b
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ExportedKeyLoader.java
@@ -0,0 +1,74 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.map.DbEntity;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+class ExportedKeyLoader extends PerEntityLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(ExportedKeyLoader.class);
+
+ ExportedKeyLoader(DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(null, config, delegate);
+ }
+
+ @Override
+ boolean shouldLoad(DbEntity entity) {
+ return delegate.dbRelationship(entity);
+ }
+
+ @Override
+ boolean catchException(DbEntity entity, SQLException ex) {
+ LOGGER.info("Error getting relationships for '"
+ + entity.getCatalog() + "." + entity.getSchema()
+ + "', ignoring. " + ex.getMessage(), ex);
+ return true;
+ }
+
+ @Override
+ ResultSet getResultSet(DbEntity dbEntity, DatabaseMetaData metaData) throws SQLException {
+ return metaData.getExportedKeys(dbEntity.getCatalog(), dbEntity.getSchema(), dbEntity.getName());
+ }
+
+ @Override
+ void processResultSet(DbEntity dbEntity, DbLoadDataStore map, ResultSet rs) throws SQLException {
+ ExportedKey key = new ExportedKey(rs);
+
+ DbEntity pkEntity = map.getDbEntity(key.getPk().getTable());
+ if (pkEntity == null) {
+ LOGGER.info("Skip relation: '" + key + "' because table '" + key.getPk().getTable() + "' not found");
+ return;
+ }
+
+ DbEntity fkEntity = map.getDbEntity(key.getFk().getTable());
+ if (fkEntity == null) {
+ LOGGER.info("Skip relation: '" + key + "' because table '" + key.getFk().getTable() + "' not found");
+ return;
+ }
+
+ map.addExportedKey(key);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/LoggingDbLoaderDelegate.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/LoggingDbLoaderDelegate.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/LoggingDbLoaderDelegate.java
new file mode 100644
index 0000000..58635f7
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/LoggingDbLoaderDelegate.java
@@ -0,0 +1,62 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import org.apache.cayenne.dbsync.reverse.dbload.DefaultDbLoaderDelegate;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DbRelationship;
+import org.apache.commons.logging.Log;
+
+/**
+ * @since 4.0
+ */
+public class LoggingDbLoaderDelegate extends DefaultDbLoaderDelegate {
+
+ private final Log logger;
+
+ public LoggingDbLoaderDelegate(Log logger) {
+ this.logger = logger;
+ }
+
+ @Override
+ public void dbEntityAdded(DbEntity entity) {
+ logger.info(" Table: " + entity.getFullyQualifiedName());
+ }
+
+ @Override
+ public void dbEntityRemoved(DbEntity entity) {
+ logger.info(" Table removed: " + entity.getFullyQualifiedName());
+ }
+
+ @Override
+ public boolean dbRelationship(DbEntity entity) {
+ if (logger.isDebugEnabled()) {
+ logger.debug(" Relationships for " + entity.getFullyQualifiedName());
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean dbRelationshipLoaded(DbEntity entity, DbRelationship relationship) {
+ logger.info(" " + relationship);
+
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerCatalogAndSchemaLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerCatalogAndSchemaLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerCatalogAndSchemaLoader.java
new file mode 100644
index 0000000..5ec1b67
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerCatalogAndSchemaLoader.java
@@ -0,0 +1,58 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.dbsync.reverse.filters.CatalogFilter;
+import org.apache.cayenne.dbsync.reverse.filters.SchemaFilter;
+
+public abstract class PerCatalogAndSchemaLoader extends AbstractLoader {
+
+ PerCatalogAndSchemaLoader(DbAdapter adapter, DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(adapter, config, delegate);
+ }
+
+ public void load(DatabaseMetaData metaData, DbLoadDataStore map) throws SQLException {
+ for (CatalogFilter catalog : config.getFiltersConfig().getCatalogs()) {
+ for (SchemaFilter schema : catalog.schemas) {
+ if(!shouldLoad(catalog, schema)) {
+ continue;
+ }
+ try (ResultSet rs = getResultSet(catalog.name, schema.name, metaData)) {
+ while (rs.next()) {
+ processResultSet(catalog, schema, map, rs);
+ }
+ }
+ }
+ }
+ }
+
+ boolean shouldLoad(CatalogFilter catalog, SchemaFilter schema) {
+ return true;
+ }
+
+ abstract ResultSet getResultSet(String catalogName, String schemaName, DatabaseMetaData metaData) throws SQLException;
+
+ abstract void processResultSet(CatalogFilter catalog, SchemaFilter schema, DbLoadDataStore map, ResultSet rs) throws SQLException;
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerEntityLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerEntityLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerEntityLoader.java
new file mode 100644
index 0000000..7a479b2
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PerEntityLoader.java
@@ -0,0 +1,64 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.map.DbEntity;
+
+public abstract class PerEntityLoader extends AbstractLoader {
+
+ PerEntityLoader(DbAdapter adapter, DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(adapter, config, delegate);
+ }
+
+ @Override
+ public void load(DatabaseMetaData metaData, DbLoadDataStore map) throws SQLException {
+ for(DbEntity dbEntity : map.getDbEntities()) {
+ if(!shouldLoad(dbEntity)) {
+ continue;
+ }
+ try(ResultSet rs = getResultSet(dbEntity, metaData)) {
+ while(rs.next()) {
+ processResultSet(dbEntity, map, rs);
+ }
+ } catch (SQLException ex) {
+ if(!catchException(dbEntity, ex)) {
+ throw ex;
+ }
+ }
+ }
+ }
+
+ boolean shouldLoad(DbEntity entity) {
+ return true;
+ }
+
+ boolean catchException(DbEntity entity, SQLException ex) {
+ return false;
+ }
+
+ abstract ResultSet getResultSet(DbEntity dbEntity, DatabaseMetaData metaData) throws SQLException;
+
+ abstract void processResultSet(DbEntity dbEntity, DbLoadDataStore map, ResultSet rs) throws SQLException;
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PrimaryKeyLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PrimaryKeyLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PrimaryKeyLoader.java
new file mode 100644
index 0000000..9a1d206
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/PrimaryKeyLoader.java
@@ -0,0 +1,60 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.map.DbAttribute;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DetectedDbEntity;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+class PrimaryKeyLoader extends PerEntityLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(PrimaryKeyLoader.class);
+
+ PrimaryKeyLoader(DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(null, config, delegate);
+ }
+
+ @Override
+ ResultSet getResultSet(DbEntity dbEntity, DatabaseMetaData metaData) throws SQLException {
+ return metaData.getPrimaryKeys(dbEntity.getCatalog(), dbEntity.getSchema(), dbEntity.getName());
+ }
+
+ @Override
+ void processResultSet(DbEntity dbEntity, DbLoadDataStore map, ResultSet rs) throws SQLException {
+ String columnName = rs.getString("COLUMN_NAME");
+ DbAttribute attribute = dbEntity.getAttribute(columnName);
+ if (attribute == null) {
+ // why an attribute might be null is not quiet clear
+ // but there is a bug report 731406 indicating that it is
+ // possible so just print the warning, and ignore
+ LOGGER.warn("Can't locate attribute for primary key: " + columnName);
+ return;
+ }
+
+ attribute.setPrimaryKey(true);
+ ((DetectedDbEntity) dbEntity).setPrimaryKeyName(rs.getString("PK_NAME"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureColumnLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureColumnLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureColumnLoader.java
new file mode 100644
index 0000000..4ff77c0
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureColumnLoader.java
@@ -0,0 +1,127 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.dba.TypesMapping;
+import org.apache.cayenne.dbsync.reverse.filters.CatalogFilter;
+import org.apache.cayenne.dbsync.reverse.filters.PatternFilter;
+import org.apache.cayenne.dbsync.reverse.filters.SchemaFilter;
+import org.apache.cayenne.map.Procedure;
+import org.apache.cayenne.map.ProcedureParameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class ProcedureColumnLoader extends PerCatalogAndSchemaLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(ProcedureColumnLoader.class);
+
+ ProcedureColumnLoader(DbAdapter adapter, DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(adapter, config, delegate);
+ }
+
+ @Override
+ protected ResultSet getResultSet(String catalogName, String schemaName, DatabaseMetaData metaData) throws SQLException {
+ return metaData.getProcedureColumns(catalogName, schemaName, WILDCARD, WILDCARD);
+ }
+
+ @Override
+ protected boolean shouldLoad(CatalogFilter catalog, SchemaFilter schema) {
+ PatternFilter filter = config.getFiltersConfig().proceduresFilter(catalog.name, schema.name);
+ return !filter.isEmpty();
+ }
+
+ @Override
+ protected void processResultSet(CatalogFilter catalog, SchemaFilter schema, DbLoadDataStore map, ResultSet rs) throws SQLException {
+ String procSchema = rs.getString("PROCEDURE_SCHEM");
+ String procCatalog = rs.getString("PROCEDURE_CAT");
+ String name = rs.getString("PROCEDURE_NAME");
+ String key = Procedure.generateFullyQualifiedName(procCatalog, procSchema, name);
+ Procedure procedure = map.getProcedure(key);
+ if (procedure == null) {
+ return;
+ }
+
+ ProcedureParameter column = loadProcedureParams(rs, key, procedure);
+ if (column == null) {
+ return;
+ }
+ procedure.addCallParameter(column);
+ }
+
+ private ProcedureParameter loadProcedureParams(ResultSet rs, String key, Procedure procedure) throws SQLException {
+ String columnName = rs.getString("COLUMN_NAME");
+
+ // skip ResultSet columns, as they are not described in Cayenne procedures yet...
+ short type = rs.getShort("COLUMN_TYPE");
+ if (type == DatabaseMetaData.procedureColumnResult) {
+ LOGGER.debug("skipping ResultSet column: " + key + "." + columnName);
+ return null;
+ }
+
+ if (columnName == null) {
+ if (type == DatabaseMetaData.procedureColumnReturn) {
+ LOGGER.debug("null column name, assuming result column: " + key);
+ columnName = "_return_value";
+ procedure.setReturningValue(true);
+ } else {
+ LOGGER.info("invalid null column name, skipping column : " + key);
+ return null;
+ }
+ }
+
+ int columnType = rs.getInt("DATA_TYPE");
+
+ // ignore precision of non-decimal columns
+ int decimalDigits = -1;
+ if (TypesMapping.isDecimal(columnType)) {
+ decimalDigits = rs.getShort("SCALE");
+ if (rs.wasNull()) {
+ decimalDigits = -1;
+ }
+ }
+
+ ProcedureParameter column = new ProcedureParameter(columnName);
+ column.setDirection(getDirection(type));
+ column.setType(columnType);
+ column.setMaxLength(rs.getInt("LENGTH"));
+ column.setPrecision(decimalDigits);
+ column.setProcedure(procedure);
+
+ return column;
+ }
+
+ private int getDirection(short type) {
+ switch (type) {
+ case DatabaseMetaData.procedureColumnIn:
+ return ProcedureParameter.IN_PARAMETER;
+ case DatabaseMetaData.procedureColumnInOut:
+ return ProcedureParameter.IN_OUT_PARAMETER;
+ case DatabaseMetaData.procedureColumnOut:
+ return ProcedureParameter.OUT_PARAMETER;
+ default:
+ return -1;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureLoader.java
new file mode 100644
index 0000000..633f033
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/ProcedureLoader.java
@@ -0,0 +1,77 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.dbsync.reverse.filters.CatalogFilter;
+import org.apache.cayenne.dbsync.reverse.filters.PatternFilter;
+import org.apache.cayenne.dbsync.reverse.filters.SchemaFilter;
+import org.apache.cayenne.map.Procedure;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class ProcedureLoader extends PerCatalogAndSchemaLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(ProcedureLoader.class);
+
+ ProcedureLoader(DbAdapter adapter, DbLoaderConfiguration config, DbLoaderDelegate delegate) {
+ super(adapter, config, delegate);
+ }
+
+ @Override
+ protected ResultSet getResultSet(String catalogName, String schemaName, DatabaseMetaData metaData) throws SQLException {
+ return metaData.getProcedures(catalogName, schemaName, WILDCARD);
+ }
+
+ @Override
+ protected boolean shouldLoad(CatalogFilter catalog, SchemaFilter schema) {
+ PatternFilter filter = config.getFiltersConfig().proceduresFilter(catalog.name, schema.name);
+ return !filter.isEmpty();
+ }
+
+ @Override
+ protected void processResultSet(CatalogFilter catalog, SchemaFilter schema, DbLoadDataStore map, ResultSet rs) throws SQLException {
+ PatternFilter filter = config.getFiltersConfig().proceduresFilter(catalog.name, schema.name);
+ String name = rs.getString("PROCEDURE_NAME");
+ if (!filter.isIncluded(name)) {
+ LOGGER.info("skipping Cayenne PK procedure: " + name);
+ return;
+ }
+
+ Procedure procedure = new Procedure(name);
+ procedure.setCatalog(rs.getString("PROCEDURE_CAT"));
+ procedure.setSchema(rs.getString("PROCEDURE_SCHEM"));
+
+ switch (rs.getShort("PROCEDURE_TYPE")) {
+ case DatabaseMetaData.procedureNoResult:
+ case DatabaseMetaData.procedureResultUnknown:
+ procedure.setReturningValue(false);
+ break;
+ case DatabaseMetaData.procedureReturnsResult:
+ procedure.setReturningValue(true);
+ break;
+ }
+ map.addProcedureSafe(procedure);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/RelationshipLoader.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/RelationshipLoader.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/RelationshipLoader.java
new file mode 100644
index 0000000..91a48f4
--- /dev/null
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/dbload/RelationshipLoader.java
@@ -0,0 +1,168 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.SQLException;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.cayenne.dbsync.naming.NameBuilder;
+import org.apache.cayenne.dbsync.naming.ObjectNameGenerator;
+import org.apache.cayenne.map.DbAttribute;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DbJoin;
+import org.apache.cayenne.map.DbRelationship;
+import org.apache.cayenne.util.EqualsBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class RelationshipLoader extends AbstractLoader {
+
+ private static final Log LOGGER = LogFactory.getLog(RelationshipLoader.class);
+
+ private final ObjectNameGenerator nameGenerator;
+
+ RelationshipLoader(DbLoaderConfiguration config, DbLoaderDelegate delegate, ObjectNameGenerator nameGenerator) {
+ super(null, config, delegate);
+ this.nameGenerator = nameGenerator;
+ }
+
+ @Override
+ public void load(DatabaseMetaData metaData, DbLoadDataStore map) throws SQLException {
+ if (config.isSkipRelationshipsLoading()) {
+ return;
+ }
+
+ for (Map.Entry<String, Set<ExportedKey>> entry : map.getExportedKeysEntrySet()) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Process keys for: " + entry.getKey());
+ }
+
+ Set<ExportedKey> exportedKeys = entry.getValue();
+ ExportedKey key = exportedKeys.iterator().next();
+ if (key == null) {
+ throw new IllegalStateException();
+ }
+
+ ExportedKey.KeyData PK = key.getPk();
+ ExportedKey.KeyData FK = key.getFk();
+ DbEntity pkEntity = map.getDbEntity(PK.getTable());
+ DbEntity fkEntity = map.getDbEntity(FK.getTable());
+ if(pkEntity == null || fkEntity == null) {
+ // Check for existence of this entities were made in creation of ExportedKey
+ throw new IllegalStateException();
+ }
+
+ if (!new EqualsBuilder()
+ .append(pkEntity.getCatalog(), PK.getCatalog())
+ .append(pkEntity.getSchema(), PK.getSchema()).append(fkEntity.getCatalog(), FK.getCatalog())
+ .append(fkEntity.getSchema(), PK.getSchema()).isEquals()) {
+
+ LOGGER.info("Skip relation: '" + key + "' because it related to objects from other catalog/schema");
+ LOGGER.info(" relation primary key: '" + PK.getCatalog() + "." + PK.getSchema() + "'");
+ LOGGER.info(" primary key entity: '" + pkEntity.getCatalog() + "." + pkEntity.getSchema() + "'");
+ LOGGER.info(" relation foreign key: '" + FK.getCatalog() + "." + FK.getSchema() + "'");
+ LOGGER.info(" foreign key entity: '" + fkEntity.getCatalog() + "." + fkEntity.getSchema() + "'");
+ continue;
+ }
+
+ // forwardRelationship is a reference from table with primary key
+ // it is what exactly we load from db
+ DbRelationship forwardRelationship = new DbRelationship();
+ forwardRelationship.setSourceEntity(pkEntity);
+ forwardRelationship.setTargetEntityName(fkEntity);
+
+ // TODO: dirty and non-transparent... using DbRelationshipDetected for the benefit of the merge package.
+ // This info is available from joins....
+ DbRelationshipDetected reverseRelationship = new DbRelationshipDetected();
+ reverseRelationship.setFkName(FK.getName());
+ reverseRelationship.setSourceEntity(fkEntity);
+ reverseRelationship.setTargetEntityName(pkEntity);
+ reverseRelationship.setToMany(false);
+
+ createAndAppendJoins(exportedKeys, pkEntity, fkEntity, forwardRelationship, reverseRelationship);
+
+ boolean toDependentPK = isToDependentPK(forwardRelationship);
+ boolean toMany = isToMany(toDependentPK, fkEntity, forwardRelationship);
+
+ forwardRelationship.setToDependentPK(toDependentPK);
+ forwardRelationship.setToMany(toMany);
+
+ // set relationship names only after their joins are ready ...
+ // generator logic is based on relationship state...
+ forwardRelationship.setName(NameBuilder
+ .builder(forwardRelationship, pkEntity)
+ .baseName(nameGenerator.relationshipName(forwardRelationship))
+ .name());
+
+ reverseRelationship.setName(NameBuilder
+ .builder(reverseRelationship, fkEntity)
+ .baseName(nameGenerator.relationshipName(reverseRelationship))
+ .name());
+
+ if (delegate.dbRelationshipLoaded(fkEntity, reverseRelationship)) {
+ fkEntity.addRelationship(reverseRelationship);
+ }
+ if (delegate.dbRelationshipLoaded(pkEntity, forwardRelationship)) {
+ pkEntity.addRelationship(forwardRelationship);
+ }
+ }
+ }
+
+ private boolean isToMany(boolean toDependentPK, DbEntity fkEntity, DbRelationship forwardRelationship) {
+ return !toDependentPK || fkEntity.getPrimaryKeys().size() != forwardRelationship.getJoins().size();
+ }
+
+ private boolean isToDependentPK(DbRelationship forwardRelationship) {
+ for (DbJoin dbJoin : forwardRelationship.getJoins()) {
+ if (!dbJoin.getTarget().isPrimaryKey()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private void createAndAppendJoins(Set<ExportedKey> exportedKeys, DbEntity pkEntity, DbEntity fkEntity,
+ DbRelationship forwardRelationship, DbRelationship reverseRelationship) {
+ for (ExportedKey exportedKey : exportedKeys) {
+ // Create and append joins
+ String pkName = exportedKey.getPk().getColumn();
+ String fkName = exportedKey.getFk().getColumn();
+
+ // skip invalid joins...
+ DbAttribute pkAtt = pkEntity.getAttribute(pkName);
+ if (pkAtt == null) {
+ LOGGER.info("no attribute for declared primary key: " + pkName);
+ continue;
+ }
+
+ DbAttribute fkAtt = fkEntity.getAttribute(fkName);
+ if (fkAtt == null) {
+ LOGGER.info("no attribute for declared foreign key: " + fkName);
+ continue;
+ }
+
+ forwardRelationship.addJoin(new DbJoin(forwardRelationship, pkName, fkName));
+ reverseRelationship.addJoin(new DbJoin(reverseRelationship, fkName, pkName));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/filters/TableFilter.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/filters/TableFilter.java b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/filters/TableFilter.java
index 44297d8..ebc2358 100644
--- a/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/filters/TableFilter.java
+++ b/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/reverse/filters/TableFilter.java
@@ -49,13 +49,18 @@ public class TableFilter {
this.excludes = excludes;
}
+ public boolean isIncludeTable(String tableName) {
+ PatternFilter columnFilter = getIncludeTableColumnFilter(tableName);
+ return columnFilter != null;
+ }
+
/**
* Return filter for columns in case we should take this table
*
* @param tableName
* @return
*/
- public PatternFilter isIncludeTable(String tableName) {
+ public PatternFilter getIncludeTableColumnFilter(String tableName) {
IncludeTableFilter include = null;
for (IncludeTableFilter p : includes) {
if (p.pattern == null || p.pattern.matcher(tableName).matches()) {
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/merge/MergeCase.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/merge/MergeCase.java b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/merge/MergeCase.java
index 63e7563..65afa21 100644
--- a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/merge/MergeCase.java
+++ b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/merge/MergeCase.java
@@ -26,9 +26,9 @@ import org.apache.cayenne.dbsync.merge.factory.MergerTokenFactory;
import org.apache.cayenne.dbsync.merge.factory.MergerTokenFactoryProvider;
import org.apache.cayenne.dbsync.naming.DefaultObjectNameGenerator;
import org.apache.cayenne.dbsync.naming.NoStemStemmer;
-import org.apache.cayenne.dbsync.reverse.db.DbLoader;
-import org.apache.cayenne.dbsync.reverse.db.DbLoaderConfiguration;
-import org.apache.cayenne.dbsync.reverse.db.LoggingDbLoaderDelegate;
+import org.apache.cayenne.dbsync.reverse.dbload.DbLoader;
+import org.apache.cayenne.dbsync.reverse.dbload.DbLoaderConfiguration;
+import org.apache.cayenne.dbsync.reverse.dbload.LoggingDbLoaderDelegate;
import org.apache.cayenne.dbsync.reverse.filters.FiltersConfig;
import org.apache.cayenne.dbsync.reverse.filters.PatternFilter;
import org.apache.cayenne.dbsync.reverse.filters.TableFilter;
@@ -112,13 +112,13 @@ public abstract class MergeCase extends DbSyncCase {
DbLoaderConfiguration loaderConfiguration = new DbLoaderConfiguration();
loaderConfiguration.setFiltersConfig(filters);
- DataMap dbImport = new DataMap();
+ DataMap dbImport;
try (Connection conn = node.getDataSource().getConnection();) {
- new DbLoader(conn,
- node.getAdapter(),
+ dbImport = new DbLoader(node.getAdapter(), conn,
+ loaderConfiguration,
new LoggingDbLoaderDelegate(LogFactory.getLog(DbLoader.class)),
new DefaultObjectNameGenerator(NoStemStemmer.getInstance()))
- .load(dbImport, loaderConfiguration);
+ .load();
} catch (SQLException e) {
throw new CayenneRuntimeException("Can't doLoad dataMap from db.", e);
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/db/DbLoaderIT.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/db/DbLoaderIT.java b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/db/DbLoaderIT.java
deleted file mode 100644
index cf154b8..0000000
--- a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/db/DbLoaderIT.java
+++ /dev/null
@@ -1,408 +0,0 @@
-/*****************************************************************
- * 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.cayenne.dbsync.reverse.db;
-
-import org.apache.cayenne.configuration.server.ServerRuntime;
-import org.apache.cayenne.dba.DbAdapter;
-import org.apache.cayenne.dba.TypesMapping;
-import org.apache.cayenne.dbsync.naming.DefaultObjectNameGenerator;
-import org.apache.cayenne.dbsync.naming.NoStemStemmer;
-import org.apache.cayenne.dbsync.reverse.filters.FiltersConfig;
-import org.apache.cayenne.dbsync.reverse.filters.PatternFilter;
-import org.apache.cayenne.dbsync.reverse.filters.TableFilter;
-import org.apache.cayenne.di.Inject;
-import org.apache.cayenne.map.DataMap;
-import org.apache.cayenne.map.DbAttribute;
-import org.apache.cayenne.map.DbEntity;
-import org.apache.cayenne.map.DbRelationship;
-import org.apache.cayenne.map.DetectedDbEntity;
-import org.apache.cayenne.map.ObjAttribute;
-import org.apache.cayenne.map.ObjEntity;
-import org.apache.cayenne.unit.UnitDbAdapter;
-import org.apache.cayenne.unit.di.server.CayenneProjects;
-import org.apache.cayenne.unit.di.server.ServerCase;
-import org.apache.cayenne.unit.di.server.ServerCaseDataSourceFactory;
-import org.apache.cayenne.unit.di.server.UseServerRuntime;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.sql.Connection;
-import java.sql.Types;
-import java.util.Collection;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
-public class DbLoaderIT extends ServerCase {
-
- public static final DbLoaderConfiguration CONFIG = new DbLoaderConfiguration();
- @Inject
- private ServerRuntime runtime;
-
- @Inject
- private DbAdapter adapter;
-
- @Inject
- private ServerCaseDataSourceFactory dataSourceFactory;
-
- @Inject
- private UnitDbAdapter accessStackAdapter;
-
- private Connection connection;
-
- private static String msgForTypeMismatch(DbAttribute origAttr, DbAttribute newAttr) {
- return msgForTypeMismatch(origAttr.getType(), newAttr);
- }
-
- private static String msgForTypeMismatch(int origType, DbAttribute newAttr) {
- String nt = TypesMapping.getSqlNameByType(newAttr.getType());
- String ot = TypesMapping.getSqlNameByType(origType);
- return attrMismatch(newAttr.getName(), "expected type: <" + ot + ">, but was <" + nt + ">");
- }
-
- private static String attrMismatch(String attrName, String msg) {
- return "[Error loading attribute '" + attrName + "': " + msg + "]";
- }
-
- @Before
- public void before() throws Exception {
- this.connection = dataSourceFactory.getSharedDataSource().getConnection();
- }
-
- private DbLoader createDbLoader(boolean meaningfulPK, boolean meaningfulFK) {
- return new DbLoader(connection, adapter, null, new DefaultObjectNameGenerator(NoStemStemmer.getInstance()));
- }
-
- @After
- public void after() throws Exception {
- connection.close();
- }
-
- @Test
- public void testGetTables() throws Exception {
-
- String tableLabel = adapter.tableTypeForTable();
-
- DbLoader loader = createDbLoader(false, false);
-
- List<DetectedDbEntity> tables = loader.createTableLoader(null, null, TableFilter.everything())
- .getDbEntities(TableFilter.everything(), new String[]{tableLabel});
-
- assertNotNull(tables);
-
- boolean foundArtist = false;
-
- for (DetectedDbEntity table : tables) {
- if ("ARTIST".equalsIgnoreCase(table.getName())) {
- foundArtist = true;
- break;
- }
- }
-
- assertTrue("'ARTIST' is missing from the table list: " + tables, foundArtist);
- }
-
- @Test
- public void testGetTablesWithWrongCatalog() throws Exception {
-
- DbLoader loader = createDbLoader(false, false);
-
- DbLoaderConfiguration config = new DbLoaderConfiguration();
- config.setFiltersConfig(
- FiltersConfig.create("WRONG", null, TableFilter.everything(), PatternFilter.INCLUDE_NOTHING));
- List<DetectedDbEntity> tables = loader
- .createTableLoader("WRONG", null, TableFilter.everything())
- .getDbEntities(TableFilter.everything(), new String[]{adapter.tableTypeForTable()});
-
- assertNotNull(tables);
- assertTrue(tables.isEmpty());
- }
-
- @Test
- public void testGetTablesWithWrongSchema() throws Exception {
-
- DbLoader loader = createDbLoader(false, false);
-
- DbLoaderConfiguration config = new DbLoaderConfiguration();
- config.setFiltersConfig(
- FiltersConfig.create(null, "WRONG", TableFilter.everything(), PatternFilter.INCLUDE_NOTHING));
- List<DetectedDbEntity> tables = loader
- .createTableLoader(null, "WRONG", TableFilter.everything())
- .getDbEntities(TableFilter.everything(), new String[]{adapter.tableTypeForTable()});
-
- assertNotNull(tables);
- assertTrue(tables.isEmpty());
- }
-
- /**
- * DataMap loading is in one big test method, since breaking it in
- * individual tests would require multiple reads of metatdata which is
- * extremely slow on some RDBMS (Sybase).
- */
- @Test
- public void testLoad() throws Exception {
- DbLoader loader = createDbLoader(false, false);
-
- boolean supportsUnique = runtime.getDataDomain().getDataNodes().iterator().next().getAdapter()
- .supportsUniqueConstraints();
- boolean supportsLobs = accessStackAdapter.supportsLobs();
- boolean supportsFK = accessStackAdapter.supportsFKConstraints();
-
- DataMap map = new DataMap();
- map.setDefaultPackage("foo.x");
-
- String tableLabel = adapter.tableTypeForTable();
-
- // *** TESTING THIS ***
- List<DbEntity> entities = loader
- .createTableLoader(null, null, TableFilter.everything())
- .loadDbEntities(map, CONFIG, new String[]{adapter.tableTypeForTable()});
-
-
- assertDbEntities(map);
-
- if (supportsLobs) {
- assertLobDbEntities(map);
- }
-
- // *** TESTING THIS ***
- loader.loadDbRelationships(CONFIG, null, null, entities);
-
- if (supportsFK) {
- Collection<DbRelationship> rels = getDbEntity(map, "ARTIST").getRelationships();
- assertNotNull(rels);
- assertTrue(!rels.isEmpty());
-
- // test one-to-one
- rels = getDbEntity(map, "PAINTING").getRelationships();
- assertNotNull(rels);
-
- // find relationship to PAINTING_INFO
- DbRelationship oneToOne = null;
- for (DbRelationship rel : rels) {
- if ("PAINTING_INFO".equalsIgnoreCase(rel.getTargetEntityName())) {
- oneToOne = rel;
- break;
- }
- }
-
- assertNotNull("No relationship to PAINTING_INFO", oneToOne);
- assertFalse("Relationship to PAINTING_INFO must be to-one", oneToOne.isToMany());
- assertTrue("Relationship to PAINTING_INFO must be to-one", oneToOne.isToDependentPK());
-
- // test UNIQUE only if FK is supported...
- if (supportsUnique) {
- assertUniqueConstraintsInRelationships(map);
- }
- }
-
- // now when the map is loaded, test
- // various things selectively check how different types were processed
- if (accessStackAdapter.supportsColumnTypeReengineering()) {
- checkTypes(map);
- }
- }
-
- private void assertUniqueConstraintsInRelationships(DataMap map) {
- // unfortunately JDBC metadata doesn't provide info for UNIQUE
- // constraints....
- // cant reengineer them...
-
- // find rel to TO_ONEFK1
- /*
- * Iterator it = getDbEntity(map,
- * "TO_ONEFK2").getRelationships().iterator(); DbRelationship rel =
- * (DbRelationship) it.next(); assertEquals("TO_ONEFK1",
- * rel.getTargetEntityName());
- * assertFalse("UNIQUE constraint was ignored...", rel.isToMany());
- */
- }
-
- private void assertDbEntities(DataMap map) {
- DbEntity dae = getDbEntity(map, "ARTIST");
- assertNotNull("Null 'ARTIST' entity, other DbEntities: " + map.getDbEntityMap(), dae);
- assertEquals("ARTIST", dae.getName().toUpperCase());
-
- DbAttribute a = getDbAttribute(dae, "ARTIST_ID");
- assertNotNull(a);
- assertTrue(a.isPrimaryKey());
- assertFalse(a.isGenerated());
-
- if (adapter.supportsGeneratedKeys()) {
- DbEntity bag = getDbEntity(map, "GENERATED_COLUMN_TEST");
- DbAttribute id = getDbAttribute(bag, "GENERATED_COLUMN");
- assertTrue(id.isPrimaryKey());
- assertTrue(id.isGenerated());
- }
- }
-
- private void assertObjEntities(DataMap map) {
-
- boolean supportsLobs = accessStackAdapter.supportsLobs();
- boolean supportsFK = accessStackAdapter.supportsFKConstraints();
-
- ObjEntity ae = map.getObjEntity("Artist");
- assertNotNull(ae);
- assertEquals("Artist", ae.getName());
-
- // assert primary key is not an attribute
- assertNull(ae.getAttribute("artistId"));
-
- if (supportsLobs) {
- assertLobObjEntities(map);
- }
-
- if (supportsFK) {
- Collection<?> rels1 = ae.getRelationships();
- assertNotNull(rels1);
- assertTrue(rels1.size() > 0);
- }
-
- assertEquals("foo.x.Artist", ae.getClassName());
- }
-
- private void assertLobDbEntities(DataMap map) {
- DbEntity blobEnt = getDbEntity(map, "BLOB_TEST");
- assertNotNull(blobEnt);
- DbAttribute blobAttr = getDbAttribute(blobEnt, "BLOB_COL");
- assertNotNull(blobAttr);
- assertTrue(msgForTypeMismatch(Types.BLOB, blobAttr), Types.BLOB == blobAttr.getType()
- || Types.LONGVARBINARY == blobAttr.getType());
-
- DbEntity clobEnt = getDbEntity(map, "CLOB_TEST");
- assertNotNull(clobEnt);
- DbAttribute clobAttr = getDbAttribute(clobEnt, "CLOB_COL");
- assertNotNull(clobAttr);
- assertTrue(msgForTypeMismatch(Types.CLOB, clobAttr), Types.CLOB == clobAttr.getType()
- || Types.LONGVARCHAR == clobAttr.getType());
-
-/*
- DbEntity nclobEnt = getDbEntity(map, "NCLOB_TEST");
- assertNotNull(nclobEnt);
- DbAttribute nclobAttr = getDbAttribute(nclobEnt, "NCLOB_COL");
- assertNotNull(nclobAttr);
- assertTrue(msgForTypeMismatch(Types.NCLOB, nclobAttr), Types.NCLOB == nclobAttr.getType()
- || Types.LONGVARCHAR == nclobAttr.getType());
-*/
- }
-
- private void assertLobObjEntities(DataMap map) {
- ObjEntity blobEnt = map.getObjEntity("BlobTest");
- assertNotNull(blobEnt);
- // BLOBs should be mapped as byte[]
- ObjAttribute blobAttr = blobEnt.getAttribute("blobCol");
- assertNotNull("BlobTest.blobCol failed to doLoad", blobAttr);
- assertEquals("byte[]", blobAttr.getType());
-
-
- ObjEntity clobEnt = map.getObjEntity("ClobTest");
- assertNotNull(clobEnt);
- // CLOBs should be mapped as Strings by default
- ObjAttribute clobAttr = clobEnt.getAttribute("clobCol");
- assertNotNull(clobAttr);
- assertEquals(String.class.getName(), clobAttr.getType());
-
-
- ObjEntity nclobEnt = map.getObjEntity("NclobTest");
- assertNotNull(nclobEnt);
- // CLOBs should be mapped as Strings by default
- ObjAttribute nclobAttr = nclobEnt.getAttribute("nclobCol");
- assertNotNull(nclobAttr);
- assertEquals(String.class.getName(), nclobAttr.getType());
- }
-
- private DbEntity getDbEntity(DataMap map, String name) {
- DbEntity de = map.getDbEntity(name);
- // sometimes table names get converted to lowercase
- if (de == null) {
- de = map.getDbEntity(name.toLowerCase());
- }
-
- return de;
- }
-
- private DbAttribute getDbAttribute(DbEntity ent, String name) {
- DbAttribute da = ent.getAttribute(name);
- // sometimes table names get converted to lowercase
- if (da == null) {
- da = ent.getAttribute(name.toLowerCase());
- }
-
- return da;
- }
-
- private DataMap originalMap() {
- return runtime.getDataDomain().getDataNodes().iterator().next().getDataMaps().iterator().next();
- }
-
- /**
- * Selectively check how different types were processed.
- */
- public void checkTypes(DataMap map) {
- DbEntity dbe = getDbEntity(map, "PAINTING");
- DbEntity floatTest = getDbEntity(map, "FLOAT_TEST");
- DbEntity smallintTest = getDbEntity(map, "SMALLINT_TEST");
- DbAttribute integerAttr = getDbAttribute(dbe, "PAINTING_ID");
- DbAttribute decimalAttr = getDbAttribute(dbe, "ESTIMATED_PRICE");
- DbAttribute varcharAttr = getDbAttribute(dbe, "PAINTING_TITLE");
- DbAttribute floatAttr = getDbAttribute(floatTest, "FLOAT_COL");
- DbAttribute smallintAttr = getDbAttribute(smallintTest, "SMALLINT_COL");
-
- // check decimal
- assertTrue(msgForTypeMismatch(Types.DECIMAL, decimalAttr), Types.DECIMAL == decimalAttr.getType()
- || Types.NUMERIC == decimalAttr.getType());
- assertEquals(2, decimalAttr.getScale());
-
- // check varchar
- assertEquals(msgForTypeMismatch(Types.VARCHAR, varcharAttr), Types.VARCHAR, varcharAttr.getType());
- assertEquals(255, varcharAttr.getMaxLength());
- // check integer
- assertEquals(msgForTypeMismatch(Types.INTEGER, integerAttr), Types.INTEGER, integerAttr.getType());
- // check float
- assertTrue(msgForTypeMismatch(Types.FLOAT, floatAttr), Types.FLOAT == floatAttr.getType()
- || Types.DOUBLE == floatAttr.getType() || Types.REAL == floatAttr.getType());
-
- // check smallint
- assertTrue(msgForTypeMismatch(Types.SMALLINT, smallintAttr), Types.SMALLINT == smallintAttr.getType()
- || Types.INTEGER == smallintAttr.getType());
- }
-
- public void checkAllDBEntities(DataMap map) {
-
- for (DbEntity origEnt : originalMap().getDbEntities()) {
- DbEntity newEnt = map.getDbEntity(origEnt.getName());
- for (DbAttribute origAttr : origEnt.getAttributes()) {
- DbAttribute newAttr = newEnt.getAttribute(origAttr.getName());
- assertNotNull("No matching DbAttribute for '" + origAttr.getName(), newAttr);
- assertEquals(msgForTypeMismatch(origAttr, newAttr), origAttr.getType(), newAttr.getType());
- // length and precision doesn't have to be the same
- // it must be greater or equal
- assertTrue(origAttr.getMaxLength() <= newAttr.getMaxLength());
- assertTrue(origAttr.getScale() <= newAttr.getScale());
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/AttributeLoaderIT.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/AttributeLoaderIT.java b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/AttributeLoaderIT.java
new file mode 100644
index 0000000..d1abac5
--- /dev/null
+++ b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/AttributeLoaderIT.java
@@ -0,0 +1,154 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.DatabaseMetaData;
+import java.sql.Types;
+
+import org.apache.cayenne.dba.TypesMapping;
+import org.apache.cayenne.map.DbAttribute;
+import org.apache.cayenne.map.DbEntity;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class AttributeLoaderIT extends BaseLoaderIT {
+
+ @Test
+ public void testAttributeLoad() throws Exception {
+ createDbEntities();
+
+ AttributeLoader loader = new AttributeLoader(adapter, EMPTY_CONFIG, new DefaultDbLoaderDelegate());
+ loader.load(connection.getMetaData(), store);
+
+ DbEntity artist = getDbEntity("ARTIST");
+ DbAttribute a = getDbAttribute(artist, "ARTIST_ID");
+ assertNotNull(a);
+ assertEquals(Types.BIGINT, a.getType());
+ assertTrue(a.isMandatory());
+ assertFalse(a.isGenerated());
+
+ a = getDbAttribute(artist, "ARTIST_NAME");
+ assertNotNull(a);
+ assertEquals(Types.CHAR, a.getType());
+ assertEquals(254, a.getMaxLength());
+ assertTrue(a.isMandatory());
+
+ a = getDbAttribute(artist, "DATE_OF_BIRTH");
+ assertNotNull(a);
+ assertEquals(Types.DATE, a.getType());
+ assertFalse(a.isMandatory());
+
+ if(accessStackAdapter.supportsLobs()) {
+ assertLobDbEntities();
+ }
+
+ if (adapter.supportsGeneratedKeys()) {
+ assertGenerated();
+ }
+ }
+
+ @Test
+ public void testAttributeLoadTypes() throws Exception {
+ DatabaseMetaData metaData = connection.getMetaData();
+ DbLoaderDelegate delegate = new DefaultDbLoaderDelegate();
+
+ // We need all data to check relationships, so simply load it all
+ EntityLoader entityLoader = new EntityLoader(adapter, EMPTY_CONFIG, delegate);
+ AttributeLoader attributeLoader = new AttributeLoader(adapter, EMPTY_CONFIG, delegate);
+
+ entityLoader.load(metaData, store);
+ attributeLoader.load(metaData, store);
+
+ DbEntity dbe = getDbEntity("PAINTING");
+ DbEntity floatTest = getDbEntity("FLOAT_TEST");
+ DbEntity smallintTest = getDbEntity("SMALLINT_TEST");
+ DbAttribute integerAttr = getDbAttribute(dbe, "PAINTING_ID");
+ DbAttribute decimalAttr = getDbAttribute(dbe, "ESTIMATED_PRICE");
+ DbAttribute varcharAttr = getDbAttribute(dbe, "PAINTING_TITLE");
+ DbAttribute floatAttr = getDbAttribute(floatTest, "FLOAT_COL");
+ DbAttribute smallintAttr = getDbAttribute(smallintTest, "SMALLINT_COL");
+
+ // check decimal
+ assertTrue(msgForTypeMismatch(Types.DECIMAL, decimalAttr), Types.DECIMAL == decimalAttr.getType()
+ || Types.NUMERIC == decimalAttr.getType());
+ assertEquals(2, decimalAttr.getScale());
+
+ // check varchar
+ assertEquals(msgForTypeMismatch(Types.VARCHAR, varcharAttr), Types.VARCHAR, varcharAttr.getType());
+ assertEquals(255, varcharAttr.getMaxLength());
+ // check integer
+ assertEquals(msgForTypeMismatch(Types.INTEGER, integerAttr), Types.INTEGER, integerAttr.getType());
+ // check float
+ assertTrue(msgForTypeMismatch(Types.FLOAT, floatAttr), Types.FLOAT == floatAttr.getType()
+ || Types.DOUBLE == floatAttr.getType() || Types.REAL == floatAttr.getType());
+
+ // check smallint
+ assertTrue(msgForTypeMismatch(Types.SMALLINT, smallintAttr), Types.SMALLINT == smallintAttr.getType()
+ || Types.INTEGER == smallintAttr.getType());
+ }
+
+ private void assertGenerated() {
+ DbEntity bag = getDbEntity("GENERATED_COLUMN_TEST");
+ DbAttribute id = getDbAttribute(bag, "GENERATED_COLUMN");
+ assertTrue(id.isGenerated());
+ }
+
+ private void assertLobDbEntities() {
+ DbEntity blobEnt = getDbEntity("BLOB_TEST");
+ assertNotNull(blobEnt);
+ DbAttribute blobAttr = getDbAttribute(blobEnt, "BLOB_COL");
+ assertNotNull(blobAttr);
+ assertTrue(msgForTypeMismatch(Types.BLOB, blobAttr), Types.BLOB == blobAttr.getType()
+ || Types.LONGVARBINARY == blobAttr.getType());
+
+ DbEntity clobEnt = getDbEntity("CLOB_TEST");
+ assertNotNull(clobEnt);
+ DbAttribute clobAttr = getDbAttribute(clobEnt, "CLOB_COL");
+ assertNotNull(clobAttr);
+ assertTrue(msgForTypeMismatch(Types.CLOB, clobAttr), Types.CLOB == clobAttr.getType()
+ || Types.LONGVARCHAR == clobAttr.getType());
+ }
+
+
+
+ private DbAttribute getDbAttribute(DbEntity ent, String name) {
+ DbAttribute da = ent.getAttribute(name);
+ // sometimes table names get converted to lowercase
+ if (da == null) {
+ da = ent.getAttribute(name.toLowerCase());
+ }
+
+ return da;
+ }
+
+ private static String msgForTypeMismatch(int origType, DbAttribute newAttr) {
+ String nt = TypesMapping.getSqlNameByType(newAttr.getType());
+ String ot = TypesMapping.getSqlNameByType(origType);
+ return attrMismatch(newAttr.getName(), "expected type: <" + ot + ">, but was <" + nt + ">");
+ }
+
+ private static String attrMismatch(String attrName, String msg) {
+ return "[Error loading attribute '" + attrName + "': " + msg + "]";
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/8c273022/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/BaseLoaderIT.java
----------------------------------------------------------------------
diff --git a/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/BaseLoaderIT.java b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/BaseLoaderIT.java
new file mode 100644
index 0000000..1edc938
--- /dev/null
+++ b/cayenne-dbsync/src/test/java/org/apache/cayenne/dbsync/reverse/dbload/BaseLoaderIT.java
@@ -0,0 +1,91 @@
+/*****************************************************************
+ * 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.cayenne.dbsync.reverse.dbload;
+
+import java.sql.Connection;
+
+import org.apache.cayenne.configuration.server.ServerRuntime;
+import org.apache.cayenne.dba.DbAdapter;
+import org.apache.cayenne.di.Inject;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.DetectedDbEntity;
+import org.apache.cayenne.unit.UnitDbAdapter;
+import org.apache.cayenne.unit.di.server.CayenneProjects;
+import org.apache.cayenne.unit.di.server.ServerCase;
+import org.apache.cayenne.unit.di.server.ServerCaseDataSourceFactory;
+import org.apache.cayenne.unit.di.server.UseServerRuntime;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.junit.Assert.assertTrue;
+
+@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
+public class BaseLoaderIT extends ServerCase {
+
+ static final DbLoaderConfiguration EMPTY_CONFIG = new DbLoaderConfiguration();
+
+ @Inject
+ protected DbAdapter adapter;
+
+ @Inject
+ protected ServerRuntime runtime;
+
+ @Inject
+ protected ServerCaseDataSourceFactory dataSourceFactory;
+
+ @Inject
+ protected UnitDbAdapter accessStackAdapter;
+
+ Connection connection;
+
+ DbLoadDataStore store;
+
+ @Before
+ public void before() throws Exception {
+ store = new DbLoadDataStore();
+ assertTrue("Store is not empty", store.getDbEntities().isEmpty());
+ this.connection = dataSourceFactory.getSharedDataSource().getConnection();
+ }
+
+ @After
+ public void after() throws Exception {
+ connection.close();
+ }
+
+ void createDbEntities() {
+ String[] names = {"ARTIST", "BLOB_TEST", "CLOB_TEST", "GENERATED_COLUMN_TEST"};
+ for(String name : names) {
+ createEntity(name);
+ }
+ }
+
+ void createEntity(String name) {
+ store.addDbEntity(new DetectedDbEntity(name));
+ }
+
+ DbEntity getDbEntity(String name) {
+ DbEntity de = store.getDbEntity(name);
+ // sometimes table names get converted to lowercase
+ if (de == null) {
+ de = store.getDbEntity(name.toLowerCase());
+ }
+ return de;
+ }
+}