Example usage for java.sql DatabaseMetaData getPrimaryKeys

List of usage examples for java.sql DatabaseMetaData getPrimaryKeys

Introduction

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

Prototype

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

Source Link

Document

Retrieves a description of the given table's primary key columns.

Usage

From source file:com.qualogy.qafe.business.resource.rdb.query.enhancer.SQLQueryEnhancer.java

public Query enhance(Query query, DatabaseMetaData databaseMetaData) throws EnhancementFailedException {
    SQLQuery sqlQuery = (SQLQuery) query;

    ResultSet resultSet = null;//  w  ww  .  jav  a2  s.  c o m

    try {
        if (StringUtils.isBlank(sqlQuery.getSqlAsAttribute()) && StringUtils.isBlank(sqlQuery.getSqlAsText())
                && StringUtils.isNotBlank(sqlQuery.getTable())) {
            // The Oracle database stores its table names as Upper-Case,
            // if you pass a table name in lowercase characters, it will not work.
            // MySQL database does not care if table name is uppercase/lowercase.
            //
            // TODO:check if there is a way to catch table data
            // TODO: dialect needed for upper/lowercase
            String userName = databaseMetaData.getUserName();
            resultSet = databaseMetaData.getTables(null, null, sqlQuery.getTable().toUpperCase(), null);

            String tableSchema = null;

            // Knowing schema name is not necessary but we gain performance
            // by using it during retrieving meta data.
            while (resultSet.next() && (null != userName)) {
                // some vendors like MySQL do not provide schema name
                // that's why we have to check whether the schema name is "null"
                if ((null != resultSet.getString("TABLE_SCHEM"))
                        && resultSet.getString("TABLE_SCHEM").equals(userName)) {
                    tableSchema = userName;

                    break;
                }

                // TABLE_TYPE
            }

            try {
                sqlQuery.getMetaData().setSupportsGetGeneratedKeys(databaseMetaData.supportsGetGeneratedKeys());
            } catch (AbstractMethodError e) {
                LOG.log(Level.WARNING,
                        "On the database driver there is no support for Metadata reading (sqlquery: "
                                + sqlQuery.getId() + ")",
                        e);
            }

            // if you pass null values for the first two parameters, then
            // it might take too long to return the result.
            resultSet = databaseMetaData.getPrimaryKeys(null, tableSchema, sqlQuery.getTable().toUpperCase());

            while (resultSet.next()) {
                sqlQuery.getMetaData().addPrimaryKey(resultSet.getString("COLUMN_NAME"));
            }

            // if no primarykeys found on a table, an update statement cannot be generated
            // so the query will be marked as error containing.
            sqlQuery.validate();
        }
    } catch (SQLException e) {
        throw new EnhancementFailedException(e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new EnhancementFailedException(e);
            }
        }
    }

    return sqlQuery;
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

/**
 * test getPrimaryKeys()// w w w  .j ava  2  s .c  o  m
 * @throws SQLException
 */
@Test
public void testPrimaryKeys() throws SQLException {
    DatabaseMetaData dbmd = con.getMetaData();
    assertNotNull(dbmd);
    // currently getPrimaryKeys always returns an empty resultset for Hive
    ResultSet res = dbmd.getPrimaryKeys(null, null, null);
    ResultSetMetaData md = res.getMetaData();
    assertEquals(md.getColumnCount(), 6);
    assertFalse(res.next());
}

From source file:com.adito.jdbc.DBDumper.java

/**
 * Dump table creation SQL. It is up to the caller to close the stream and connections when
 * finished with.//from  w  w w  . j a v a2s  .com
 * 
 * @param writer write SQL to this writer.
 * @param conx connection to get data from
 * @param quoteChar character to use to quote strings
 * @param tables array of table names or <code>null</code> to dump all in
 *        database
 * @throws Exception on any error
 */
public void dumpTable(PrintWriter writer, JDBCConnectionImpl conx, char quoteChar, String[] tables)
        throws Exception {
    Connection jdbcConnection = conx.getConnection();
    DatabaseMetaData dbMetaData = jdbcConnection.getMetaData();

    if (tables == null) {
        ResultSet rs = dbMetaData.getTables(null, null, null, null);
        try {
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                String tableType = rs.getString("TABLE_TYPE");
                if (tableType.equalsIgnoreCase("TABLE")) {
                    dumpTable(writer, conx, quoteChar, new String[] { tableName });
                }
            }
        } finally {
            rs.close();
        }
    } else {
        for (int i = 0; i < tables.length; i++) {
            String tableName = tables[i];
            log.info("Dumping table creation for " + tableName);
            writer.println("CREATE TABLE " + tableName + " (");
            boolean first = true;

            // Columns
            ResultSet rs2 = dbMetaData.getColumns(null, null, tableName, "%");
            try {
                while (rs2.next()) {
                    if (first) {
                        first = false;
                    } else {
                        writer.println(",");
                    }
                    String columnName = rs2.getString("COLUMN_NAME");
                    String columnType = rs2.getString("TYPE_NAME");
                    int columnSize = rs2.getInt("COLUMN_SIZE");
                    String nullable = rs2.getString("IS_NULLABLE");
                    String nullString = "NULL";
                    if ("NO".equalsIgnoreCase(nullable)) {
                        nullString = "NOT NULL";
                    }
                    writer.print("    " + columnName + " " + columnType);
                    if (columnSize != 0) {
                        if (columnType.equalsIgnoreCase("varchar") && columnSize > 255) {
                            columnSize = 255;
                        }
                        writer.print(" (" + columnSize + ")");
                    }
                    writer.print(" " + nullString);

                }
            } finally {
                rs2.close();
            }

            // Keys
            try {
                rs2 = dbMetaData.getPrimaryKeys(null, null, tableName);
                String primaryKeyName = null;
                StringBuffer primaryKeyColumns = new StringBuffer();
                while (rs2.next()) {
                    String thisKeyName = rs2.getString("PK_NAME");
                    if ((thisKeyName != null && primaryKeyName == null)
                            || (thisKeyName == null && primaryKeyName != null)
                            || (thisKeyName != null && !thisKeyName.equals(primaryKeyName))
                            || (primaryKeyName != null && !primaryKeyName.equals(thisKeyName))) {
                        if (primaryKeyColumns.length() > 0) {
                            writer.print(",\n    PRIMARY KEY ");
                            if (primaryKeyName != null) {
                                writer.print(primaryKeyName);
                            }
                            writer.print("(" + primaryKeyColumns.toString() + ")");
                        }
                        primaryKeyColumns = new StringBuffer();
                        primaryKeyName = thisKeyName;
                    }
                    if (primaryKeyColumns.length() > 0) {
                        primaryKeyColumns.append(", ");
                    }
                    primaryKeyColumns.append(rs2.getString("COLUMN_NAME"));
                }
                if (primaryKeyColumns.length() > 0) {
                    writer.print(",\n    PRIMARY KEY ");
                    if (primaryKeyName != null) {
                        writer.print(primaryKeyName);
                    }
                    writer.print(" (" + primaryKeyColumns.toString() + ")");
                }
            } finally {
                rs2.close();
            }
            writer.println("\n);");
            writer.println();
        }
    }
}

From source file:org.alinous.plugin.mysql.MySQLDataSource.java

private void setupDataTableColumns(DatabaseMetaData metaData, DataTable dataTable, String tableName)
        throws SQLException {
    ResultSet trs = metaData.getColumns(null, null, tableName, null);
    while (trs.next()) {
        String columnName = trs.getString("COLUMN_NAME");
        String columnType = trs.getString("TYPE_NAME");

        DataField fld = new DataField();
        fld.setName(columnName);//from w ww  .j av a  2 s  .  c  o  m

        // setType for MYSQL
        if (columnType.toUpperCase().equals("VARCHAR") || columnType.toUpperCase().equals("CHAR")) {
            fld.setType(DataField.TYPE_STRING);
        } else if (columnType.toUpperCase().equals("TEXT")) {
            fld.setType(DataField.TYPE_TEXT_STRING);
        } else if (columnType.toUpperCase().equals("TINYINT") || columnType.toUpperCase().equals("INTEGER")
                || columnType.toUpperCase().equals("BIGINT")) {
            fld.setType(DataField.TYPE_INTEGER);
        } else if (columnType.toUpperCase().equals("TIMESTAMP")
                || columnType.toUpperCase().equals("DATETIME")) {
            fld.setType(DataField.TYPE_TIMESTAMP);
        } else if (columnType.toUpperCase().equals("DATE")) {
            fld.setType(DataField.TYPE_DATE);
        } else if (columnType.toUpperCase().equals("FLOAT") || columnType.toUpperCase().equals("DOUBLE")) {
            fld.setType(DataField.TYPE_DOUBLE);
        } else {
            fld.setType(DataField.TYPE_STRING);
        }

        dataTable.addField(fld);
    }

    // PrimaryKeys
    ResultSet primarysRs = metaData.getPrimaryKeys(null, null, tableName);
    while (primarysRs.next()) {
        String columnName = primarysRs.getString("COLUMN_NAME");

        DataField fld = dataTable.getDataField(columnName);
        fld.setPrimary(true);
        dataTable.addPrimaryKey(fld.getName());
    }
    primarysRs.close();
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testParentReferences() throws Exception {
    /* Test parent references from Statement */
    Statement s = this.con.createStatement();
    ResultSet rs = s.executeQuery("SELECT * FROM " + dataTypeTableName);

    assertTrue(s.getConnection() == this.con);
    assertTrue(rs.getStatement() == s);//  www.  j av a2 s. c o  m

    rs.close();
    s.close();

    /* Test parent references from PreparedStatement */
    PreparedStatement ps = this.con.prepareStatement("SELECT * FROM " + dataTypeTableName);
    rs = ps.executeQuery();

    assertTrue(ps.getConnection() == this.con);
    assertTrue(rs.getStatement() == ps);

    rs.close();
    ps.close();

    /* Test DatabaseMetaData queries which do not have a parent Statement */
    DatabaseMetaData md = this.con.getMetaData();

    assertTrue(md.getConnection() == this.con);

    rs = md.getCatalogs();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getFunctions(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getImportedKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getPrimaryKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedureColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedures(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getSchemas();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTableTypes();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTables(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTypeInfo();
    assertNull(rs.getStatement());
    rs.close();
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseHost.java

/**
 * Returns the columns of the specified database object.
 *
 * @param catalog the table catalog name
 * @param schema the table schema name//  www.ja v a  2 s.co m
 * @param table the database object name
 * @return the columns
 */
public List<DatabaseColumn> getColumns(String catalog, String schema, String table) throws DataSourceException {

    ResultSet rs = null;

    List<DatabaseColumn> columns = new ArrayList<DatabaseColumn>();

    try {
        String _catalog = getCatalogNameForQueries(catalog);
        String _schema = getSchemaNameForQueries(schema);
        DatabaseMetaData dmd = getDatabaseMetaData();

        // retrieve the base column info
        rs = dmd.getColumns(_catalog, _schema, table, null);

        /*
        if (Log.isDebugEnabled()) {
                
        Log.debug("Meta data on columns for table - " + table);
                
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
                    
            Log.debug("Column: [ " + (i + 1) + " ] " + metaData.getColumnName(i + 1));                    
        }
        }
        */

        while (rs.next()) {

            DefaultDatabaseColumn column = new DefaultDatabaseColumn();
            column.setCatalogName(catalog);
            column.setSchemaName(schema);
            column.setName(rs.getString(4));
            column.setTypeInt(rs.getInt(5));
            column.setTypeName(rs.getString(6));
            column.setColumnSize(rs.getInt(7));
            column.setColumnScale(rs.getInt(9));
            column.setRequired(rs.getInt(11) == DatabaseMetaData.columnNoNulls);
            column.setRemarks(rs.getString(12));
            column.setDefaultValue(rs.getString(13));
            columns.add(column);
        }
        releaseResources(rs);

        int columnCount = columns.size();
        if (columnCount > 0) {

            // check for primary keys
            rs = dmd.getPrimaryKeys(_catalog, _schema, table);
            while (rs.next()) {

                String pkColumn = rs.getString(4);

                // find the pk column in the previous list
                for (int i = 0; i < columnCount; i++) {

                    DatabaseColumn column = columns.get(i);
                    String columnName = column.getName();

                    if (columnName.equalsIgnoreCase(pkColumn)) {
                        ((DefaultDatabaseColumn) column).setPrimaryKey(true);
                        break;
                    }

                }

            }
            releaseResources(rs);

            // check for foreign keys
            rs = dmd.getImportedKeys(_catalog, _schema, table);
            while (rs.next()) {
                String fkColumn = rs.getString(8);

                // find the fk column in the previous list
                for (int i = 0; i < columnCount; i++) {
                    DatabaseColumn column = columns.get(i);
                    String columnName = column.getName();
                    if (columnName.equalsIgnoreCase(fkColumn)) {
                        ((DefaultDatabaseColumn) column).setForeignKey(true);
                        break;
                    }
                }

            }

        }

        return columns;

    } catch (SQLException e) {

        if (Log.isDebugEnabled()) {

            Log.error("Error retrieving column data for table " + table + " using connection "
                    + getDatabaseConnection(), e);
        }

        return columns;

        //            throw new DataSourceException(e);

    } finally {

        releaseResources(rs);
    }

}

From source file:com.oltpbenchmark.catalog.Catalog.java

/**
 * Construct the set of Table objects from a given Connection handle
 * @param conn/* w  w  w .j ava2s. c om*/
 * @return
 * @throws SQLException
 * @see http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
 */
protected void init() throws SQLException {
    // Load the database's DDL
    this.benchmark.createDatabase(DB_TYPE, this.conn);

    // TableName -> ColumnName -> <FkeyTable, FKeyColumn>
    Map<String, Map<String, Pair<String, String>>> foreignKeys = new HashMap<String, Map<String, Pair<String, String>>>();

    DatabaseMetaData md = conn.getMetaData();
    ResultSet table_rs = md.getTables(null, null, null, new String[] { "TABLE" });
    while (table_rs.next()) {
        if (LOG.isDebugEnabled())
            LOG.debug(SQLUtil.debug(table_rs));
        String internal_table_name = table_rs.getString(3);
        String table_name = origTableNames.get(table_rs.getString(3).toUpperCase());
        assert (table_name != null) : "Unexpected table '" + table_rs.getString(3) + "' from catalog";
        LOG.debug(String.format("ORIG:%s -> CATALOG:%s", internal_table_name, table_name));

        String table_type = table_rs.getString(4);
        if (table_type.equalsIgnoreCase("TABLE") == false)
            continue;
        Table catalog_tbl = new Table(table_name);

        // COLUMNS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving COLUMN information for " + table_name);
        ResultSet col_rs = md.getColumns(null, null, internal_table_name, null);
        while (col_rs.next()) {
            if (LOG.isTraceEnabled())
                LOG.trace(SQLUtil.debug(col_rs));
            String col_name = col_rs.getString(4);
            int col_type = col_rs.getInt(5);
            String col_typename = col_rs.getString(6);
            Integer col_size = col_rs.getInt(7);
            String col_defaultValue = col_rs.getString(13);
            boolean col_nullable = col_rs.getString(18).equalsIgnoreCase("YES");
            boolean col_autoinc = false; // FIXME col_rs.getString(22).toUpperCase().equals("YES");

            Column catalog_col = new Column(catalog_tbl, col_name, col_type, col_typename, col_size);
            catalog_col.setDefaultValue(col_defaultValue);
            catalog_col.setAutoincrement(col_autoinc);
            catalog_col.setNullable(col_nullable);
            // FIXME col_catalog.setSigned();

            if (LOG.isDebugEnabled())
                LOG.debug(
                        String.format("Adding %s.%s [%s / %d]", table_name, col_name, col_typename, col_type));
            catalog_tbl.addColumn(catalog_col);
        } // WHILE
        col_rs.close();

        // PRIMARY KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving PRIMARY KEY information for " + table_name);
        ResultSet pkey_rs = md.getPrimaryKeys(null, null, internal_table_name);
        SortedMap<Integer, String> pkey_cols = new TreeMap<Integer, String>();
        while (pkey_rs.next()) {
            String col_name = pkey_rs.getString(4);
            assert (catalog_tbl.getColumnByName(col_name) != null) : String
                    .format("Unexpected primary key column %s.%s", table_name, col_name);
            int col_idx = pkey_rs.getShort(5);
            // HACK: SQLite doesn't return the KEY_SEQ, so if we get back
            //       a zero for this value, then we'll just length of the pkey_cols map
            if (col_idx == 0)
                col_idx = pkey_cols.size();
            LOG.debug(String.format("PKEY[%02d]: %s.%s", col_idx, table_name, col_name));
            assert (pkey_cols.containsKey(col_idx) == false);
            pkey_cols.put(col_idx, col_name);
        } // WHILE
        pkey_rs.close();
        catalog_tbl.setPrimaryKeyColumns(pkey_cols.values());

        // INDEXES
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving INDEX information for " + table_name);
        ResultSet idx_rs = md.getIndexInfo(null, null, internal_table_name, false, false);
        while (idx_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(SQLUtil.debug(idx_rs));
            boolean idx_unique = (idx_rs.getBoolean(4) == false);
            String idx_name = idx_rs.getString(6);
            int idx_type = idx_rs.getShort(7);
            int idx_col_pos = idx_rs.getInt(8) - 1;
            String idx_col_name = idx_rs.getString(9);
            String sort = idx_rs.getString(10);
            SortDirectionType idx_direction;
            if (sort != null) {
                idx_direction = sort.equalsIgnoreCase("A") ? SortDirectionType.ASC : SortDirectionType.DESC;
            } else
                idx_direction = null;

            Index catalog_idx = catalog_tbl.getIndex(idx_name);
            if (catalog_idx == null) {
                catalog_idx = new Index(catalog_tbl, idx_name, idx_type, idx_unique);
                catalog_tbl.addIndex(catalog_idx);
            }
            assert (catalog_idx != null);
            catalog_idx.addColumn(idx_col_name, idx_direction, idx_col_pos);
        } // WHILE
        idx_rs.close();

        // FOREIGN KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving FOREIGN KEY information for " + table_name);
        ResultSet fk_rs = md.getImportedKeys(null, null, internal_table_name);
        foreignKeys.put(table_name, new HashMap<String, Pair<String, String>>());
        while (fk_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(table_name + " => " + SQLUtil.debug(fk_rs));
            assert (fk_rs.getString(7).equalsIgnoreCase(table_name));

            String colName = fk_rs.getString(8);
            String fk_tableName = origTableNames.get(fk_rs.getString(3).toUpperCase());
            String fk_colName = fk_rs.getString(4);

            foreignKeys.get(table_name).put(colName, Pair.of(fk_tableName, fk_colName));
        } // WHILE
        fk_rs.close();

        tables.put(table_name, catalog_tbl);
    } // WHILE
    table_rs.close();

    // FOREIGN KEYS
    if (LOG.isDebugEnabled())
        LOG.debug("Foreign Key Mappings:\n" + StringUtil.formatMaps(foreignKeys));
    for (Table catalog_tbl : tables.values()) {
        Map<String, Pair<String, String>> fk = foreignKeys.get(catalog_tbl.getName());
        for (Entry<String, Pair<String, String>> e : fk.entrySet()) {
            String colName = e.getKey();
            Column catalog_col = catalog_tbl.getColumnByName(colName);
            assert (catalog_col != null);

            Pair<String, String> fkey = e.getValue();
            assert (fkey != null);

            Table fkey_tbl = tables.get(fkey.first);
            if (fkey_tbl == null) {
                throw new RuntimeException("Unexpected foreign key parent table " + fkey);
            }
            Column fkey_col = fkey_tbl.getColumnByName(fkey.second);
            if (fkey_col == null) {
                throw new RuntimeException("Unexpected foreign key parent column " + fkey);
            }

            if (LOG.isDebugEnabled())
                LOG.debug(catalog_col.fullName() + " -> " + fkey_col.fullName());
            catalog_col.setForeignKey(fkey_col);
        } // FOR
    } // FOR

    return;
}

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;
                }/*w ww .  j a  v a2s.  co m*/
                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:jef.database.DbMetaData.java

/**
 * //w ww .  j a va 2s. c  om
 * 
 * @param tableName
 *            ??
 * @return Map<String,String> key=?? value=??
 */
public Optional<PrimaryKey> getPrimaryKey(String tableName) throws SQLException {
    tableName = MetaHolder.toSchemaAdjustedName(tableName);
    tableName = info.profile.getObjectNameToUse(tableName);
    Connection conn = getConnection(false);
    DatabaseMetaData databaseMetaData = conn.getMetaData();
    ResultSet rs = null;
    PrimaryKey pk = null;
    List<PairIS> pkColumns = new ArrayList<PairIS>();
    try {
        rs = databaseMetaData.getPrimaryKeys(null, schema, tableName);
        while (rs.next()) {
            String pkName = rs.getString("PK_NAME");
            String col = rs.getString("COLUMN_NAME");
            int seq = rs.getShort("KEY_SEQ");
            if (pk == null) {
                pk = new PrimaryKey(pkName);
            }
            pkColumns.add(new PairIS(seq, col));
        }
        if (pk == null)
            return Optional.empty();
    } finally {
        DbUtils.close(rs);
        releaseConnection(conn);
    }
    pkColumns.sort((a, b) -> Integer.compare(a.first, b.first));
    String[] columns = new String[pkColumns.size()];
    for (int i = 0; i < pkColumns.size(); i++) {
        columns[i] = pkColumns.get(i).second;
    }
    pk.setColumns(columns);
    return Optional.of(pk);

}

From source file:org.openconcerto.sql.model.SQLTable.java

/**
 * Fetch fields from the passed args./*from w  ww  .  j a  va2  s  .  co m*/
 * 
 * @param metaData the metadata.
 * @param rs the resultSet of a getColumns(), the cursor must be on a row.
 * @param version the version of the schema.
 * @return whether the <code>rs</code> has more row.
 * @throws SQLException if an error occurs.
 * @throws IllegalStateException if the current row of <code>rs</code> doesn't describe this.
 */
boolean fetchFields(DatabaseMetaData metaData, ResultSet rs, String version) throws SQLException {
    if (!this.isUs(rs))
        throw new IllegalStateException("rs current row does not describe " + this);

    synchronized (getTreeMutex()) {
        synchronized (this) {
            this.version = version;

            // we need to match the database ordering of fields
            final LinkedHashMap<String, SQLField> newFields = new LinkedHashMap<String, SQLField>();
            // fields
            boolean hasNext = true;
            while (hasNext && this.isUs(rs)) {
                final SQLField f = SQLField.create(this, rs);
                newFields.put(f.getName(), f);
                hasNext = rs.next();
            }

            final List<String> newPrimaryKeys = new ArrayList<String>();
            final ResultSet pkRS = metaData.getPrimaryKeys(this.getBase().getMDName(),
                    this.getSchema().getName(), this.getName());
            while (pkRS.next()) {
                newPrimaryKeys.add(pkRS.getString("COLUMN_NAME"));
            }

            this.setState(newFields, newPrimaryKeys, null);

            return hasNext;
        }
    }
}