Exemplo n.º 1
0
  /**
   * Read metadata about a table from the database.
   *
   * @param table The RDBMS table.
   * @return A map of information about the columns. The key is the name of the column, a String;
   *     the value is a ColumnInfo object.
   * @exception SQLException If there is a problem retrieving information from the RDBMS.
   */
  private static Map<String, ColumnInfo> retrieveColumnInfo(String table) throws SQLException {
    Connection connection = null;
    ResultSet pkcolumns = null;
    ResultSet columns = null;

    try {
      String schema = ConfigurationManager.getProperty("db.schema");
      if (StringUtils.isBlank(schema)) {
        schema = null;
      }
      String catalog = null;

      int dotIndex = table.indexOf('.');
      if (dotIndex > 0) {
        catalog = table.substring(0, dotIndex);
        table = table.substring(dotIndex + 1, table.length());
        log.warn("catalog: " + catalog);
        log.warn("table: " + table);
      }

      connection = getConnection();

      DatabaseMetaData metadata = connection.getMetaData();
      Map<String, ColumnInfo> results = new HashMap<String, ColumnInfo>();

      int max = metadata.getMaxTableNameLength();
      String tname = ((max > 0) && (table.length() >= max)) ? table.substring(0, max - 1) : table;

      pkcolumns = metadata.getPrimaryKeys(catalog, schema, tname);

      Set<String> pks = new HashSet<String>();

      while (pkcolumns.next()) {
        pks.add(pkcolumns.getString(4));
      }

      columns = metadata.getColumns(catalog, schema, tname, null);

      while (columns.next()) {
        String column = columns.getString(4);
        ColumnInfo cinfo = new ColumnInfo();
        cinfo.setName(column);
        cinfo.setType((int) columns.getShort(5));

        if (pks.contains(column)) {
          cinfo.setIsPrimaryKey(true);
        }

        results.put(column, cinfo);
      }

      return Collections.unmodifiableMap(results);
    } finally {
      if (pkcolumns != null) {
        try {
          pkcolumns.close();
        } catch (SQLException sqle) {
        }
      }

      if (columns != null) {
        try {
          columns.close();
        } catch (SQLException sqle) {
        }
      }

      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException sqle) {
        }
      }
    }
  }