List of usage examples for java.sql DatabaseMetaData getCrossReference
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException;
From source file:org.apache.ambari.server.orm.DBAccessorImpl.java
@Override public boolean tableHasForeignKey(String tableName, String referenceTableName, String[] keyColumns, String[] referenceColumns) throws SQLException { DatabaseMetaData metaData = getDatabaseMetaData(); //NB: reference table contains pk columns while key table contains fk columns ResultSet rs = metaData.getCrossReference(null, null, convertObjectName(referenceTableName), null, null, convertObjectName(tableName)); List<String> pkColumns = new ArrayList<String>(referenceColumns.length); for (String referenceColumn : referenceColumns) { pkColumns.add(convertObjectName(referenceColumn)); }/* w w w . ja v a 2 s.c om*/ List<String> fkColumns = new ArrayList<String>(keyColumns.length); for (String keyColumn : keyColumns) { fkColumns.add(convertObjectName(keyColumn)); } if (rs != null) { try { while (rs.next()) { String pkColumn = rs.getString("PKCOLUMN_NAME"); String fkColumn = rs.getString("FKCOLUMN_NAME"); int pkIndex = pkColumns.indexOf(pkColumn); int fkIndex = fkColumns.indexOf(fkColumn); if (pkIndex != -1 && fkIndex != -1) { if (pkIndex != fkIndex) { LOG.warn("Columns for FK constraint should be provided in exact order"); } else { pkColumns.remove(pkIndex); fkColumns.remove(fkIndex); } } else { LOG.debug("pkCol={}, fkCol={} not found in provided column names, skipping", pkColumn, fkColumn); //TODO debug } } if (pkColumns.isEmpty() && fkColumns.isEmpty()) { return true; } } finally { rs.close(); } } return false; }