Example usage for java.sql DatabaseMetaData getCrossReference

List of usage examples for java.sql DatabaseMetaData getCrossReference

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getCrossReference.

Prototype

ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
        String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException;

Source Link

Document

Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).

Usage

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;

}