Example usage for java.sql DatabaseMetaData getImportedKeys

List of usage examples for java.sql DatabaseMetaData getImportedKeys

Introduction

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

Prototype

ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException;

Source Link

Document

Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table).

Usage

From source file:org.nextframework.persistence.exception.SQLServerSQLErrorCodeSQLExceptionTranslator.java

@Override
protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
    //TODO ARRUMAR ESSA DESORDEM (FAZER HIGH COHESION.. LOW COUPLING)
    //System.out.println(task+" - "+sql);
    //      boolean matcher2 = false;
    if (sqlEx.getErrorCode() == 547) {
        //exceo de FK
        Matcher matcher = pattern.matcher(sqlEx.getMessage());
        if (!matcher.find()) {
            //tentar segundo pattern
            matcher = pattern2.matcher(sqlEx.getMessage());
            if (!matcher.find()) {
                return null;
            } else {
                //               matcher2 = true;
            }/*from   w  ww .  jav  a  2  s  . c om*/
        }
        String fk_name = matcher.group(2);
        String fk_table_name = matcher.group(3).toUpperCase();
        if (fk_table_name.lastIndexOf('.') > 0) {
            fk_table_name = fk_table_name.substring(fk_table_name.lastIndexOf('.') + 1);
        }
        String pk_table_name = null;
        String fkTableDisplayName = null;
        String pkTableDisplayName = null;
        try {
            DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
            ResultSet importedKeys = metaData.getImportedKeys(null, null, fk_table_name);

            while (importedKeys.next()) {
                if (importedKeys.getString("FK_NAME").equals(fk_name)) {
                    pk_table_name = importedKeys.getString("PKTABLE_NAME");
                    if (pk_table_name != null) {
                        pk_table_name = pk_table_name.toUpperCase();
                    }
                }
            }
        } catch (SQLException e) {
            //se nao conseguir o metadata .. vazar
            log.warn("No foi possvel conseguir o metadata do banco para ler informacoes de FK.");
            return null;
        }

        Class<?>[] entities = ClassManagerFactory.getClassManager().getClassesWithAnnotation(Entity.class);
        pkTableDisplayName = pk_table_name;
        fkTableDisplayName = fk_table_name;
        for (Class<?> entityClass : entities) {
            String tableName = getTableName(entityClass);
            if (tableName.equals(pk_table_name)) {
                pkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
            if (tableName.equals(fk_table_name)) {
                fkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
        }

        String mensagem = null;
        sql = matcher.group(1);
        if (sql.toLowerCase().trim().startsWith("delete")) {
            mensagem = "No foi possvel remover " + pkTableDisplayName
                    + ". Existe(m) registro(s) vinculado(s) em " + fkTableDisplayName + ".";
        } else if (sql.toLowerCase().trim().startsWith("update")) {
            mensagem = "No foi possvel atualizar " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        } else if (sql.toLowerCase().trim().startsWith("insert")) {
            mensagem = "No foi possvel inserir " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        } else {
            mensagem = "No foi possvel efetuar operao em " + pkTableDisplayName
                    + ". Existe(m) registro(s) vinculado(s) em " + fkTableDisplayName + ".";
        }
        return new ForeignKeyException(mensagem, new ForeignKeyException(task));
    }

    return null;
}

From source file:org.openconcerto.sql.model.graph.DatabaseGraph.java

private void map(final DBRoot r, final String tableName, final Set<String> tableNames) throws SQLException {
    // either we refresh the whole root and we must know which tables to use
    // or we refresh only one table and tableNames is useless
    assert tableName == null ^ tableNames == null;
    final SetMap<String, String> metadataFKs = new SetMap<String, String>();
    @SuppressWarnings("unchecked")
    final List<Object[]> importedKeys = this.base.getDataSource()
            .useConnection(new ConnectionHandlerNoSetup<List, SQLException>() {
                @Override//from w  w w  .  j a  va2 s . c o  m
                public List handle(final SQLDataSource ds) throws SQLException {
                    final DatabaseMetaData metaData = ds.getConnection().getMetaData();
                    return (List) SQLDataSource.ARRAY_LIST_HANDLER.handle(metaData
                            .getImportedKeys(r.getBase().getMDName(), r.getSchema().getName(), tableName));
                }
            });
    // accumulators for multi-field foreign key
    final List<SQLField> from = new ArrayList<SQLField>();
    final List<SQLField> to = new ArrayList<SQLField>();
    final SQLSystem sys = this.base.getServer().getSQLSystem();
    Rule updateRule = null;
    Rule deleteRule = null;
    String name = null;
    // Follow the JDBC to the letter and order by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME,
    // KEY_SEQ : thus ignoring FK_NAME
    if (sys == SQLSystem.MSSQL) {
        Collections.sort(importedKeys, IMPORTED_KEYS_COMP);
    }
    final Iterator<Object[]> ikIter = importedKeys.iterator();
    while (ikIter.hasNext()) {
        final Object[] m = ikIter.next();

        // FKTABLE_SCHEM
        assert CompareUtils.equals(m[5], r.getSchema().getName());
        // FKTABLE_NAME
        final String fkTableName = (String) m[6];
        assert tableName == null || tableName.equals(fkTableName);
        if (tableNames != null && !tableNames.contains(fkTableName))
            continue;
        // not by name, postgresql returns lowercase
        // "FKCOLUMN_NAME"
        final String keyName = (String) m[7];
        // "KEY_SEQ"
        final short seq = ((Number) m[8]).shortValue();
        // "PKCOLUMN_NAME"
        final String foreignTableColName = (String) m[3];
        // "FK_NAME"
        final String foreignKeyName = (String) m[11];

        final SQLField key = r.getTable(fkTableName).getField(keyName);

        final SQLTable foreignTable;
        try {
            foreignTable = getTableFromJDBCMetaData(r.getBase(), (String) m[0], (String) m[1], (String) m[2]);
        } catch (Exception e) {
            throw new IllegalStateException("Could not find what " + key.getSQLName() + " references", e);
        }

        metadataFKs.add(fkTableName, keyName);
        if (seq == 1) {
            // if we start a new link add the current one
            if (from.size() > 0)
                addLink(from, to, name, updateRule, deleteRule);
            from.clear();
            to.clear();
        }
        from.add(key);
        assert seq == 1 || from.get(from.size() - 2).getTable() == from.get(from.size() - 1).getTable();
        to.add(foreignTable.getField(foreignTableColName));
        assert seq == 1 || to.get(to.size() - 2).getTable() == to.get(to.size() - 1).getTable();

        final Rule prevUpdateRule = updateRule;
        final Rule prevDeleteRule = deleteRule;
        // "UPDATE_RULE"
        updateRule = getRule((Number) m[9], sys);
        // "DELETE_RULE"
        deleteRule = getRule((Number) m[10], sys);
        if (seq > 1) {
            if (prevUpdateRule != updateRule)
                throw new IllegalStateException(
                        "Incoherent update rules " + prevUpdateRule + " != " + updateRule);
            if (prevDeleteRule != deleteRule)
                throw new IllegalStateException(
                        "Incoherent delete rules " + prevDeleteRule + " != " + deleteRule);
        }

        name = foreignKeyName;
        // MAYBE DEFERRABILITY
    }
    if (from.size() > 0)
        addLink(from, to, name, updateRule, deleteRule);

    if (Boolean.getBoolean(INFER_FK)) {
        final Set<String> tables = tableName != null ? Collections.singleton(tableName) : tableNames;
        for (final String tableToInfer : tables) {
            final SQLTable table = r.getTable(tableToInfer);
            final Set<String> lexicalFKs = SQLKey.foreignKeys(table);
            // already done
            lexicalFKs.removeAll(metadataFKs.getNonNull(table.getName()));
            // MAYBE option to print out foreign keys w/o constraint
            for (final String keyName : lexicalFKs) {
                final SQLField key = table.getField(keyName);
                addLink(singletonList(key), singletonList(SQLKey.keyToTable(key).getKey()), null, null, null);
            }
        }
    }
}

From source file:org.openmrs.module.spreadsheetimport.DatabaseBackend.java

private static void reverseEngineerDatabaseTable() throws Exception {
    tableColumnMap = new TreeMap<String, String>();
    tableColumnListMap = new TreeMap<String, List<String>>();
    Connection conn = null;//ww  w. j a  va 2s .co m
    Exception exception = null;
    try {
        // Connect to db
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Properties p = Context.getRuntimeProperties();
        String url = p.getProperty("connection.url");

        conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
                p.getProperty("connection.password"));

        // All tables
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getTables(null, null, "", null);
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");

            // All columns
            List<String> columnNames = new ArrayList<String>();
            ResultSet rsColumns = dmd.getColumns(null, null, tableName, "");
            while (rsColumns.next()) {
                columnNames.add(rsColumns.getString("COLUMN_NAME"));
            }
            rsColumns.close();

            //            // Remove imported keys
            ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName);
            while (rsImportedKeys.next()) {
                String columnName = rsImportedKeys.getString("FKCOLUMN_NAME");
                if (columnNames.contains(columnName) && "obs".equalsIgnoreCase(tableName)
                        && !"value_coded".equalsIgnoreCase(columnName)) { // hack: only allow obs.value_coded to go through
                    columnNames.remove(columnName);
                }
            }
            rsImportedKeys.close();

            List<String> clonedColumns = new ArrayList<String>();
            clonedColumns.addAll(columnNames);

            // Add to map
            for (String columnName : clonedColumns) {
                String tableDotColumn = tableName + "." + columnName;
                tableColumnMap.put(tableDotColumn, makePrettyTableDotColumn(tableDotColumn));
            }

            // Remove primary key
            ResultSet rsPrimaryKeys = dmd.getPrimaryKeys(null, null, tableName);
            while (rsPrimaryKeys.next()) {
                String columnName = rsPrimaryKeys.getString("COLUMN_NAME");
                if (columnNames.contains(columnName)) {
                    columnNames.remove(columnName);
                }
            }
            rsPrimaryKeys.close();

            tableColumnListMap.put(tableName, columnNames);

        }
    } catch (Exception e) {
        log.debug(e.toString());
        exception = e;
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }

    if (exception != null) {
        throw exception;
    }
}

From source file:org.openmrs.module.spreadsheetimport.DatabaseBackend.java

public static Map<String, String> getMapOfImportedKeyTableNameToColumnNamesForTable(String tableName)
        throws Exception {
    Map<String, String> result = new HashMap<String, String>();
    Connection conn = null;/*from w ww .ja v  a2 s  . co m*/
    Exception exception = null;
    try {
        // Connect to db
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Properties p = Context.getRuntimeProperties();
        String url = p.getProperty("connection.url");

        conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
                p.getProperty("connection.password"));

        // Not NULLable columns
        DatabaseMetaData dmd = conn.getMetaData();
        List<String> columnNames = new ArrayList<String>();
        ResultSet rsColumns = dmd.getColumns(null, null, tableName, "");
        while (rsColumns.next()) {
            if (!rsColumns.getString("IS_NULLABLE").equals("YES")) {
                columnNames.add(rsColumns.getString("COLUMN_NAME"));
            }
        }
        rsColumns.close();

        // Imported keys
        ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName);
        while (rsImportedKeys.next()) {
            String columnName = rsImportedKeys.getString("FKCOLUMN_NAME");
            if (columnNames.contains(columnName)) {
                result.put(rsImportedKeys.getString("PKTABLE_NAME"), columnName);
            }
        }
        rsImportedKeys.close();
    } catch (Exception e) {
        log.debug(e.toString());
        exception = e;
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }

    if (exception != null) {
        throw exception;
    } else {
        return result;
    }
}

From source file:org.seasar.dbflute.logic.jdbc.metadata.basic.DfForeignKeyExtractor.java

protected ResultSet extractForeignKeyMetaData(DatabaseMetaData metaData, UnifiedSchema unifiedSchema,
        String tableName, boolean retry) throws SQLException {
    try {/*from w ww. j  av a2 s  .  c om*/
        final String catalogName = unifiedSchema.getPureCatalog();
        final String schemaName = unifiedSchema.getPureSchema();
        return metaData.getImportedKeys(catalogName, schemaName, tableName);
    } catch (SQLException e) {
        if (retry) {
            // because the exception may be thrown when the table is not found
            return null;
        } else {
            throw e;
        }
    }
}

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

private void fillPkandFk(ColumnSet colSet, Map<String, TdColumn> columnMap, DatabaseMetaData dbJDBCMetadata,
        String catalogName, String schemaName, String tableName) throws Exception {
    if (columnMap.size() > 0) {
        Map<String, ForeignKey> foreignKeysMap = new HashMap<String, ForeignKey>();
        if (orgomg.cwm.resource.relational.RelationalPackage.eINSTANCE.getTable()
                .isSuperTypeOf(colSet.eClass())) {
            try {
                // primary key
                // MOD qiongli 2011-2-21,bug 18828 ,Access database dosen't support 'getPrimaryKeys(...)'.
                if (MetadataConnectionUtils.isOdbcExcel(dbJDBCMetadata)
                        || MetadataConnectionUtils.isAccess(dbJDBCMetadata)
                        || MetadataConnectionUtils.isHive(dbJDBCMetadata)) {
                    log.info("This database don't support primary key and foreign key"); //$NON-NLS-1$
                    return;
                }//  ww  w . ja v a  2s  .  com
                ResultSet pkResult = dbJDBCMetadata.getPrimaryKeys(catalogName, schemaName, tableName);
                PrimaryKey primaryKey = null;
                while (pkResult.next()) {
                    String colName = pkResult.getString(GetPrimaryKey.COLUMN_NAME.name());
                    String pkName = pkResult.getString(GetPrimaryKey.PK_NAME.name());
                    if (pkName == null) {
                        continue;
                    }
                    if (primaryKey == null) {
                        primaryKey = orgomg.cwm.resource.relational.RelationalFactory.eINSTANCE
                                .createPrimaryKey();
                        primaryKey.setName(pkName);
                    } else if (!pkName.equals(primaryKey.getName())) {
                        throw new Exception("the table" + colSet + " have two or more primaryKeys"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    columnMap.get(colName).getUniqueKey().add(primaryKey);
                    columnMap.get(colName).setKey(true);
                    TableHelper.addPrimaryKey((TdTable) colSet, primaryKey);
                }
                pkResult.close();
                // foreign key
                ForeignKey foreignKey = null;
                ResultSet fkResult = null;
                try {
                    // some databases (eg. sqlite) jave not yet implemented this method
                    fkResult = dbJDBCMetadata.getImportedKeys(catalogName, schemaName, tableName);
                } catch (Exception e) {
                    log.warn(e, e);
                }
                if (fkResult != null) {
                    while (fkResult.next()) {
                        String fkname = fkResult.getString(GetForeignKey.FK_NAME.name());
                        String colName = fkResult.getString(GetForeignKey.FKCOLUMN_NAME.name());
                        if (foreignKey == null || foreignKeysMap.get(fkname) == null) {
                            foreignKey = orgomg.cwm.resource.relational.RelationalFactory.eINSTANCE
                                    .createForeignKey();
                            foreignKey.setName(fkname);
                            foreignKeysMap.put(fkname, foreignKey);
                        }
                        columnMap.get(colName).getKeyRelationship().add(foreignKey);
                    }
                    fkResult.close();
                    TableHelper.addForeignKeys((TdTable) colSet, Arrays.asList(
                            foreignKeysMap.values().toArray(new ForeignKey[foreignKeysMap.values().size()])));
                }
            } catch (SQLException e) {
                log.error(e, e);
            }
        }
    }
}

From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java

public List<DBColumn> getColumns(String schema, String table)
        throws NextSqlException, MalformedTableNameException {

    Connection con;/*  w ww.j ava  2 s.c  o m*/
    List<DBColumn> columns = new ArrayList<DBColumn>();
    String schemaName;
    String escapedTableName;
    try {
        con = Globals.getConnection();
        if (schema == null) {
            schemaName = Globals.getConnection().getMetaData().getUserName();
        } else {
            schemaName = schema;
        }

        Dialect dialect = Globals.getDialect();
        if (dialect.isKeyWord(table)) {
            escapedTableName = dialect.getEscapedKeyWord(table);
        } else {
            escapedTableName = table;
        }

    } catch (Exception e) {
        throw new NextSqlException("Could not retrieve connection.", e);
    }

    ResultSet rs = null;
    Statement stmt = null;
    List<String> keyColumns = new ArrayList<String>();
    try {
        // primary keys
        DatabaseMetaData dbmd = con.getMetaData();
        rs = dbmd.getPrimaryKeys(null, schemaName, table);
        while (rs.next()) {
            keyColumns.add(rs.getString("COLUMN_NAME"));
        }
        closeResultSet(rs);

        // foreign keys
        rs = dbmd.getImportedKeys(null, schemaName, table);
        List<String> foreignColumns = new ArrayList<String>();
        HashMap<String, DBForeignColumnInfo> fkMap = new HashMap<String, DBForeignColumnInfo>();
        while (rs.next()) {
            String fkSchema = rs.getString("FKTABLE_SCHEM");
            String fkTable = rs.getString("FKTABLE_NAME");
            String fkColumn = rs.getString("FKCOLUMN_NAME");
            String pkSchema = rs.getString("PKTABLE_SCHEM");
            String pkTable = rs.getString("PKTABLE_NAME");
            String pkColumn = rs.getString("PKCOLUMN_NAME");
            DBForeignColumnInfo fkInfo = new DBForeignColumnInfo(fkSchema, fkTable, fkColumn, pkSchema, pkTable,
                    pkColumn);
            //System.out.println("fkInfo :  " + fkInfo);
            foreignColumns.add(fkColumn);
            fkMap.put(fkColumn, fkInfo);
        }
        closeResultSet(rs);

        // column names with index
        rs = dbmd.getIndexInfo(null, schemaName, table, false, true);
        List<String> indexes = new ArrayList<String>();
        while (rs.next()) {
            String indexName = rs.getString(9);
            if (indexName != null) {
                indexes.add(indexName);
            }
        }
        closeResultSet(rs);

        DataSource ds = DefaultDataSourceManager.getInstance().getConnectedDataSource();
        String header = "";
        stmt = con.createStatement();
        try {
            // workaround if a table name contains spaces
            if (escapedTableName.indexOf(" ") != -1) {
                escapedTableName = "\"" + escapedTableName + "\"";
            }
            String prefix = "";
            if (!NO_SCHEMA_NAME.equals(schemaName)) {
                prefix = schemaName;
            }
            if (prefix.indexOf(" ") != -1) {
                prefix = "\"" + prefix + "\"";
            }
            if (!"".equals(prefix)) {
                prefix = prefix + ".";
            }

            if (ds.getDriver().equals(CSVDialect.DRIVER_CLASS)) {
                header = (String) ds.getProperties().get("headerline");
                if (header == null) {
                    header = "";
                }
            }
            if (header.isEmpty()) {
                String s = "SELECT * FROM " + prefix + escapedTableName + " WHERE 1 = 0";
                LOG.info("getColumns[ " + s + "]");
                rs = stmt.executeQuery(s);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            throw new MalformedTableNameException(e);
        }

        if (header.isEmpty()) {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for (int col = 1; col <= columnCount; col++) {
                String name = rsmd.getColumnLabel(col);
                int length = rsmd.getColumnDisplaySize(col);
                int precision = rsmd.getPrecision(col);
                int scale = rsmd.getScale(col);
                boolean isPrimaryKey = false;
                boolean isForeignKey = false;
                boolean isIndex = false;
                if (keyColumns.contains(name)) {
                    isPrimaryKey = true;
                }
                DBForeignColumnInfo fkInfo = null;
                if (foreignColumns.contains(name)) {
                    isForeignKey = true;
                    fkInfo = fkMap.get(name);
                }
                if (indexes.contains(name)) {
                    isIndex = true;
                }
                DBColumn column = new DBColumn(schemaName, table, name, rsmd.getColumnTypeName(col),
                        isPrimaryKey, isForeignKey, isIndex, fkInfo, length, precision, scale);
                columns.add(column);
            }
        } else {
            String columnTypes = (String) ds.getProperties().get("columnTypes");
            String[] names = header.split(",");
            String[] types = new String[names.length];
            for (int i = 0; i < types.length; i++) {
                types[i] = "String";
            }
            if ((columnTypes != null) && !columnTypes.isEmpty()) {
                types = columnTypes.split(",");
            }
            for (int i = 0; i < names.length; i++) {
                DBColumn column = new DBColumn(schemaName, table, names[i], types[i], false, false, false, null,
                        20, 0, 0);
                columns.add(column);
            }

        }
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
        e.printStackTrace();
        throw new NextSqlException("SQL Exception: " + e.getMessage(), e);
    } finally {
        closeResultSet(rs);
        closeStatement(stmt);
    }
    return columns;
}

From source file:ua.utility.kfsdbupgrade.App.java

/**
 * Gets the indexes from a {@link DatabaseMetaData} for a given
 * <code>table</code> and creates and returns a {@link Set} of
 * {@link String} SQL UPDATE statements that will create those indexes on a
 * database./*from ww  w.  j  a  v a 2  s . c  om*/
 * 
 * @param dmd
 *            {@link DatabaseMetaData} to get index information from
 * @param table
 *            {@link String} of the specific table to get index information
 *            for
 * @return {@link Set} of {@link String} SQL UPDATE statements that will
 *         create those indexes on a database.
 */
private Set<String> loadForeignKeyIndexInformation(DatabaseMetaData dmd, String table) {
    Set<String> retval = new HashSet<String>();

    ResultSet res = null;
    try {
        Map<String, ForeignKeyReference> fkeys = new HashMap<String, ForeignKeyReference>();
        Map<String, TableIndexInfo> tindexes = new HashMap<String, TableIndexInfo>();
        res = dmd.getImportedKeys(null, getSchema(), table);
        boolean foundfk = false;

        while (res.next()) {
            foundfk = true;
            // FKCOLUMN_NAME String => foreign key column name
            String fcname = res.getString(8);
            /*
             * KEY_SEQ short => sequence number within a foreign key( a
             * value of 1 represents the first column of the foreign key, a
             * value of 2 would represent the second column within the
             * foreign key)
             */
            int seq = res.getInt(9);
            // 12 - FK_NAME String => foreign key name (may be null)
            String fkname = res.getString(12);

            ForeignKeyReference fkref = fkeys.get(fkname);

            if (fkref == null) {
                fkeys.put(fkname,
                        fkref = new ForeignKeyReference(getSchema(), table, fkname, INDEX_NAME_TEMPLATE));
            }

            ColumnInfo cinfo = new ColumnInfo(fcname, seq);

            cinfo.setNumeric(isNumericColumn(dmd, getSchema(), table, fcname));

            fkref.addColumn(cinfo);
        }

        res.close();

        if (foundfk) {
            tindexes.put(table, loadTableIndexInfo(dmd, table));
        }

        List<ForeignKeyReference> l = new ArrayList<ForeignKeyReference>(fkeys.values());

        Collections.sort(l);

        Iterator<ForeignKeyReference> it = l.iterator();

        while (it.hasNext()) {
            ForeignKeyReference fkref = it.next();
            if (hasIndex(tindexes.get(fkref.getTableName()).getIndexes(), fkref)) {
                it.remove();
            } else {
                String s = fkref.getCreateIndexString(tindexes.get(fkref.getTableName()));
                if (StringUtils.isNotBlank(fkref.getIndexName())) {
                    retval.add(s);
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    } finally {
        closeDbObjects(null, null, res);
    }

    return retval;
}

From source file:uk.ac.ed.epcc.webapp.model.data.Repository.java

/** Set the table References for the fields  
 * //www.  java  2  s. co m
 * @param ctx
 * @param c
 * @throws SQLException 
 */
private void setReferences(AppContext ctx, Connection c) throws SQLException {
    //Logger log = ctx.getService(LoggerService.class).getLogger(getClass());
    //log.debug("SetReferences for "+getTable());
    // look for foreign keys to identify remote tables.
    DatabaseMetaData meta = c.getMetaData();
    ResultSet rs = meta.getImportedKeys(c.getCatalog(), null, table_name);
    if (rs.first()) {
        //log.debug("Have foreign key");
        do {
            String field = rs.getString("FKCOLUMN_NAME");
            String table = rs.getString("PKTABLE_NAME");
            String key_name = rs.getString("FK_NAME");
            short seq = rs.getShort("KEY_SEQ");
            if (seq == 1) {
                FieldInfo info = fields.get(field);
                if (info.isNumeric()) {
                    String name = REFERENCE_PREFIX + param_name + "." + info.getName(false);
                    table = ctx.getInitParameter(name, table); // use param in preference because of windows case mangle
                    String tag = TableToTag(ctx, table);
                    //log.debug("field "+field+" references "+table);
                    info.setReference(true, key_name, tag);
                }
            }
        } while (rs.next());
    }
    // now try explicit references set from properties
    for (FieldInfo i : fields.values()) {
        if (i.getReferencedTable() == null) {
            //use param name for table rename
            String tag = REFERENCE_PREFIX + param_name + "." + i.getName(false);
            String table = ctx.getInitParameter(tag);
            //log.debug("tag "+tag+" resolves to "+table);
            i.setReference(false, null, table);
        }
    }
}