getIndexInfo returning wrong unique columns for composite primary keys

為{幸葍}努か 提交于 2021-02-08 08:00:14

问题


I am working with JDBC and I have created a simple table using postgresql:

create table bank (
    bank_id int,
    bank_name varchar(40),
    bank_address varchar(80),
    user_id int,
    user_first_name varchar(40),
    user_surname varchar(40),
    user_phone varchar(12),
    primary key(bank_id, user_id)
);

The problem is that when I check whether bank_id is unique, I get true (when I was expecting false, ofc). Here is the code for my function that checks whether a column in a table is unique:

private static boolean checkIfUnique(Connection conn, String tableName,
    String columnName) {

    try {
        DatabaseMetaData meta = conn.getMetaData();
        ResultSet rs = meta.getIndexInfo(null, null, tableName, true, true);

        while(rs.next()) {
            if (rs.getString(9).equals(columnName)) {
                return true;
            }
        }

        return false;

    } catch (Exception e) {

        System.err.println("Exception: " + e + "\n" + e.getMessage());
    }

    return false;
}  

I'm not really sure what I did wrong. Any suggestion would help. Thank you.


回答1:


getIndexInfo() returns one row for each column and index. And both columns are part of the primary key, so you get two rows in the ResultSet, one for each column.

If you want to check if a column is unique "on its own", you also need to count how many rows getIndexInfo() returned for each index.

In your case the ResultSet would look something like this:

TABLE_NAME  | INDEX_NAME  | COLUMN_NAME
------------+-------------+------------
bank        | bank_pkey   | bank_id
bank        | bank_pkey   | user_id

Note there might be more unique indexes in that result!

If there was a unique index on only bank_id, you would have something like this:

TABLE_NAME  | INDEX_NAME  | COLUMN_NAME
------------+-------------+------------
bank        | idx_bank_id | bank_id

Only then, the column would be unique.

So in the loop you also need to count the number of columns per index in which the column to check participates. Only if the total number of columns in that index is one you can say that the column is unique.



来源:https://stackoverflow.com/questions/52059015/getindexinfo-returning-wrong-unique-columns-for-composite-primary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!