Example #1
0
  /**
   * Returns a table's foreign keys and their columns as a Map from the key name to the ForeignKey
   * object.
   *
   * <p>A foreign key may not have a name. On such a database, 2 foreign keys must reference 2
   * different tables. Otherwise there's no way to tell them apart and the foreign key information
   * reported by DatabaseMetaData becomes ill-formed.
   */
  public static Map<String, ForeignKey> getForeignKeys(DatabaseMetaData metadata, String tableName)
      throws Exception {
    ResultSet keys =
        metadata.getImportedKeys(
            metadata.getConnection().getCatalog(), metadata.getUserName(), tableName);
    Map<String, ForeignKey> map = new HashMap<String, ForeignKey>();

    while (keys.next()) {
      String table = keys.getString(IMPORTED_PK_TAB_NAME);
      String name = keys.getString(IMPORTED_FK_KEY_NAME);
      if (name == null || name.length() == 0) name = "UNNAMED_FK_" + table;

      ForeignKey key = map.get(name);
      if (key == null) {
        map.put(name, key = new ForeignKey(table));
      }
      key.add(keys.getString(IMPORTED_FK_COL_NAME));
    }
    keys.close();
    return map;
  }